是的,要使用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" } ] }