为此,可以将$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 } ] }