让我们创建一个包含文档的集合-
> db.demo313.insertOne({"_id":100,"details":[{"Name":"Chris","Age":24}]}); { "acknowledged" : true, "insertedId" : 100 } > db.demo313.insertOne({"_id":101,"details":[{"Name":"David","Age":22}]}); { "acknowledged" : true, "insertedId" : 101 } > db.demo313.insertOne({"_id":102,"details":[{"Name":"Mike","Age":25}]}); { "acknowledged" : true, "insertedId" : 102 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo313.find();
这将产生以下输出-
{ "_id" : 100, "details" : [ { "Name" : "Chris", "Age" : 24 } ] } { "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] } { "_id" : 102, "details" : [ { "Name" : "Mike", "Age" : 25 } ] }
以下是在MongoDB中将文件与$elemMatch匹配的查询-
db.demo313.find({_id:101},{details: { $elemMatch: { Age: 22 } } } );
这将产生以下输出-
{ "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] }