How to retrieve all matching elements present inside array in Mongo DB?

痞子三分冷 提交于 2019-12-08 06:39:59

问题


I have document shown below:

{
  name: "testing",
  place:"London",
  documents: [ 
                        {   
                            x:1,
                            y:2,
                        },
                        {
                            x:1,
                            y:3,
                        },
                        {
                            x:4,
                            y:3,
                        }
            ]
    }

I want to retrieve all matching documents i.e. I want o/p in below format:

{
    name: "testing",
    place:"London",
    documents: [ 
                        {   
                            x:1,
                            y:2,
                        },
                        {
                            x:1,
                            y:3,
                        }

            ]
    }

What I have tried is :

db.test.find({"documents.x": 1},{_id: 0, documents: {$elemMatch: {x: 1}}});

But, it gives first entry only.


回答1:


As JohnnyHK said, the answer in MongoDB: select matched elements of subcollection explains it well.

In your case, the aggregate would look like this:

(note: the first match is not strictly necessary, but it helps in regards of performance (can use index) and memory usage ($unwind on a limited set)

> db.xx.aggregate([
...      // find the relevant documents in the collection
...      // uses index, if defined on documents.x
...      { $match: { documents: { $elemMatch: { "x": 1 } } } }, 
...      // flatten array documennts
...      { $unwind : "$documents" },
...      // match for elements, "documents" is no longer an array
...      { $match: { "documents.x" : 1 } },
...      // re-create documents array
...      { $group : { _id : "$_id", documents : { $addToSet : "$documents" } }}
... ]);
{
    "result" : [
        {
            "_id" : ObjectId("515e2e6657a0887a97cc8d1a"),
            "documents" : [
                {
                    "x" : 1,
                    "y" : 3
                },
                {
                    "x" : 1,
                    "y" : 2
                }
            ]
        }
    ],
    "ok" : 1
}

For more information about aggregate(), see http://docs.mongodb.org/manual/applications/aggregation/



来源:https://stackoverflow.com/questions/15429243/how-to-retrieve-all-matching-elements-present-inside-array-in-mongo-db

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