2

I have a document structure as follows:

{
    "field1": "value",
    "field2": "value",
    "items": [
        {
            "inField1": "value1",
            "inField2": "value2",
            "votes": {
                "count": 2,
                "people": [
                    {
                        "username": "user1",
                        "image": "http://image/to/user1/profile.jpg"
                    },
                    {
                        "username": "user2",
                        "image": "http://image/to/user2/profile.jpg"
                    }
                ]
            }
        },
        {
            "inField1": "value3",
            "inField2": "value4",
            "votes": {
                "count": 1,
                "people": [
                    {
                        "username": "user1",
                        "image": "http://image/to/user1/profile.jpg"
                    }
                ]
            }
        }
    ]
}

Now I need all item(single Object of items field) where in any people property of votes property has a username as user1?

In above mentioned example it should return both the items, as both of them contain user1 in username property, but if I search for user2 then onl the first item should be returned.

Community
  • 1
  • 1
HVT7
  • 709
  • 4
  • 13
  • 23

2 Answers2

3

The answer to this question was found in another SO link: https://stackoverflow.com/a/20155210/2641194

First, we have to $unwind both the arrays and then data for each people is a separate document, and then our $match comes into picture to pick out only those who satisfy the query:

db.collection('topic').aggregate(
    [{
        "$unwind": "$items"
    }, {
        "$unwind": "$items.votes.people"
    }, {
        "$match": {
            "items.votes.people.username": "user2"
        }
    }], function(err, docs) {
        if(!err) {
            docs.forEach(function(doc) {
                // code
            });

        } else {
            console.log(err);
        }
        db.close();
    });

If you need to further understand $unwind, and how does it work then please refer to this mongodb documentation link: https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

Community
  • 1
  • 1
HVT7
  • 709
  • 4
  • 13
  • 23
1

Use Aggregation framework, First unwind items array and match them.

Try this:

db.getCollection('test').aggregate(
    [{
        "$unwind": "$items"
    }, {
        "$match": {
            "items.votes.people.username": "user2"
        }
    }]
)
Hiren S.
  • 2,793
  • 15
  • 25