是否可以使用 MongoDB 查询数组中对象中字段具有特定值のエントリ?
是的,要使用 MongoDB 查询数组中对象中的字段,请使用以下语法 −
db.yourCollectionName.find({"yourOuterFieldName": { $elemMatch: { "yourInnerFieldName": "yourValue" } } } ).pretty();
为了理解以上概念,让我们创建一个包含文档的集合。创建包含文档的集合的查询如下 −
> db.objectInAnArrayDemo.insertOne({ "StudentDetails": [{ "StudentName": "John", "StudentMessage": "Hi"}, {"StudentName": "Larry", "StudentMessage": "Hello"}]}) { "acknowledged" : true, "insertedId" : ObjectId("5c92635d36de59bd9de06381") } > db.objectInAnArrayDemo.insertOne({ "StudentDetails": [{ "StudentName": "Carol", "StudentMessage": "Hello"}, {"StudentName": "David", "StudentMessage": "Good Morning"}]}) { "acknowledged" : true, "insertedId" : ObjectId("5c92637936de59bd9de06382") }
使用 find() 方法从集合中显示所有文档。查询如下 −
> db.objectInAnArrayDemo.find().pretty();
以下是输出 −
{ "_id" : ObjectId("5c92635d36de59bd9de06381"), "StudentDetails" : [ { "StudentName" : "John", "StudentMessage" : "Hi" }, { "StudentName" : "Larry", "StudentMessage" : "Hello" } ] } { "_id" : ObjectId("5c92637936de59bd9de06382"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentMessage" : "Hello" }, { "StudentName" : "David", "StudentMessage" : "Good Morning" } ] }
以下是使用 MongoDB 查询数组中对象的字段 −
> db.objectInAnArrayDemo.find({"StudentDetails": { $elemMatch: { "StudentMessage": "Good Morning" } } } ).pretty();
以下是输出 −
{ "_id" : ObjectId("5c92637936de59bd9de06382"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentMessage" : "Hello" }, { "StudentName" : "David", "StudentMessage" : "Good Morning" } ] }
广告