MongoDB 使用 $elemMatch 匹配文档
让我们创建一个包含文档的集合 -
> 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 } ] }
以下是使用 $elemMatch 在 MongoDB 中匹配文档的查询 -
db.demo313.find({_id:101},{details: { $elemMatch: { Age: 22 } } } );
这将产生以下输出 -
{ "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] }
广告