Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

The following is my subdocument:

{

    "_id" : ObjectId("512e28984815cbfcb21646a7"),

    "list" : [

        {

            "a" : 1

        },

        {

            "a" : 2

        },

        {

            "a" : 3

        },

        {

            "a" : 4

        },

        {

            "a" : 5

        }

    ]

}

I want to filter the above subdocument as a>3. I want the following result:

{

    "_id" : ObjectId("512e28984815cbfcb21646a7"),

    "list" : [

        {

            "a" : 4

        },

        {

            "a" : 5

        }

    ]

}

I have tried the following implementation but it only returns one element:

db.test.find( { _id" : ObjectId("512e28984815cbfcb21646a7") }, { 

    list: { 

        $elemMatch: 

            { a: { $gt:3 } 

            } 

    } 

} )

The output is as follows:

{ "_id" : ObjectId("512e28984815cbfcb21646a7"), "list" : [ { "a" : 4 } ] }

Can someone guide me?

1 Answer

0 votes
by (107k points)

The approach I would suggest is aggregation. First of all, you have to perform $unwind on the list array and then implement $match. It will filter each and every element of the array and then after filtering, put it back together with the help of $group. For implementing the above-suggested tasks, refer to the following code:

db.test.aggregate([

    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},

    { $unwind: '$list'},

    { $match: {'list.a': {$gt: 3}}},

    { $group: {_id: '$_id', list: {$push: '$list.a'}}}

])

The output is aas follows:

{

  "result": [

    {

      "_id": ObjectId("512e28984815cbfcb21646a7"),

      "list": [

        4,

        5

      ]

    }

  ],

  "ok": 1

}

If you are a beginner and want to know more about MongoDB, then check out the mongodb tutorial.

Related questions

0 votes
1 answer
asked Feb 16, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
0 votes
0 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...