Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 467
Sachin Avatar asked Oct 20 '25 06:10

Sachin


1 Answers

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/

like image 88
ronasta Avatar answered Oct 22 '25 20:10

ronasta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!