db.users.find()
{
_id : ObjectId(5a7d12871541ff3ed0bb9c79) ,
users: [{“id”: 1, “name”:”user1″}, {“id”: 2, “name”: “user2”}]
}
Does mongodb support direct query of subdocuments?
db.users.find({ “user.id” : 1 })
{
_id : ObjectId(5a7d12871541ff3ed0bb9c79) ,
users: [{“id”: 1, “name”:”user1″}, {“id”: 2, “name”: “user2”}]
}
This is the document, but I want to get {id:1,name:user1}, how should this statement be written?
If it can be determined that only one array element meets the requirements, the simplest way to write it is:
rs0:PRIMARY> db.users.find({ "users.id" : 1 }, {"users.$.id": 1}) { "_id" : ObjectId("5a7d12871541ff3ed0bb9c79"), "users" : [ { "id" : 1, "name" : "user1" } ] }
If not, then
$
Only the first element satisfying the condition will be returned. To want all the elements, you need aggregation:db.users.aggregate([ {$match: {"users.id": 1}}, { $project: { users: { $filter: { input: "$users", as: "user", cond: { $eq: ["$$user.id", 1] } } } } } ]);