MongoDB get all embedded documents where condition is met

北城余情 提交于 2020-01-06 05:17:24

问题


I did this in my mongodb:

db.teams.insert({name:"Alpha team",employees:[{name:"john"},{name:"david"}]});
db.teams.insert({name:"True team",employees:[{name:"oliver"},{name:"sam"}]});
db.teams.insert({name:"Blue team",employees:[{name:"jane"},{name:"raji"}]});
db.teams.find({"employees.name":/.*o.*/});

But what I got was:

{ "_id" : ObjectId("5ddf3ca83c182cc5354a15dd"), "name" : "Alpha team", "employees" : [ { "name" : "john" }, { "name" : "david" } ] }
{ "_id" : ObjectId("5ddf3ca93c182cc5354a15de"), "name" : "True team", "employees" : [ { "name" : "oliver" }, { "name" : "sam" } ] }

But what I really want is

[{"name":"john"},{"name":"oliver"}]

I'm having a hard time finding examples of this without using some kind of programmatic iterator/loop. Or examples I find return the parent document, which means I'd have to parse out the embedded array employees and do some kind of UNION statement?

Eg.

How to get embedded document in mongodb? Retrieve only the queried element in an object array in MongoDB collection

Can someone point me in the right direction?


回答1:


Please add projections to filter out the fields you don't need. Please refer the project link mongodb projections

Your find query should be constructed with the projection parameters like below:

db.teams.find({"employees.name":/.*o.*/}, {_id:0, "employees.name": 1});

This will return you:

[{"name":"john"},{"name":"oliver"}]



回答2:


Can be solved with a simple aggregation pipeline.

db.teams.aggregate([
    {$unwind : "$employees"},
    {$match : {"employees.name":/.*o.*/}},
])

EDIT:

OP Wants to skip the parent fields. Modified query:

db.teams.aggregate([
    {$unwind : "$employees"},
    {$match : {"employees.name":/.*o.*/}},
    {$project : {"name":"$employees.name",_id:0}}
])

Output:

{ "name" : "john" }
{ "name" : "oliver" }


来源:https://stackoverflow.com/questions/59081371/mongodb-get-all-embedded-documents-where-condition-is-met

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!