配列に特定の属性を含むMongoDBドキュメントを取得します
このために、ドット(。)表記と一緒に$andを使用できます。まず、ドキュメントを使用してコレクションを作成しましょう-
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b56e25ddae1f53b62219")
}
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b58625ddae1f53b6221a")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-
> db.demo2.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e08b56e25ddae1f53b62219"),
"StudentInformation" : [
{
"StudentName" : "John",
"StudentAge" : 21
},
{
"StudentName" : "Mike",
"StudentAge" : 22
}
]
}
{
"_id" : ObjectId("5e08b58625ddae1f53b6221a"),
"StudentInformation" : [
{
"StudentName" : "Carol",
"StudentAge" : 19
},
{
"StudentName" : "Bob",
"StudentAge" : 18
}
]
} 以下は、配列内の特定の属性を含むドキュメントを取得するためのクエリです-
>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]}); これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] } -
MongoDBドキュメントの特定のフィールドから配列要素の数を取得しますか?
特定のフィールドから配列要素をカウントするには、MongoDBで$sizeを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo723.insertOne({"Subject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab094d43417811278f588a") } >
-
MongoDBを使用して、特定のネストされたドキュメントのオブジェクトの配列をクエリしますか?
ネストされたドキュメントのオブジェクトの配列をクエリするには、find()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo763.insertOne( ... { ... _id:1, ... CountryName:"US", ... "studentInformation": [ ... {