Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo db Query to filter nested array of objects in document

I have the following document

{
    "userid": "5a88389c9108bf1c48a1a6a7",
    "email": "[email protected]",
    "lastName": "abc",
    "firstName": "xyz",
    "__v": 0,
    "friends": [{
        "userid": "5a88398b9108bf1c48a1a6a9",
        "ftype": "SR",
        "status": "ACCEPT",
        "_id": ObjectId("5a9585b401ef0033cc8850c7")
    },
    {
        "userid": "5a88398b9108bf1c48a1a6a91111",
        "ftype": "SR",
        "status": "ACCEPT",
        "_id": ObjectId("5a9585b401ef0033cc8850c71111")
    },
    {
        "userid": "5a8ae0a20df6c13dd81256e0",
        "ftype": "SR",
        "status": "pending",
        "_id": ObjectId("5a9641fbbc9ef809b0f7cb4e")
    }]
},
{
    "userid": "5a88398b9108bf1c48a1a6a9",
    "friends": [{ }],
    "lastName": "123",
    "firstName": "xyz",
    .......
},
{
    "userid": "5a88398b9108bf1c48a1a6a91111",
    "friends": [{ }],
    "lastName": "456",
    "firstName": "xyz",
    ...
}   
  • First Query

Here I want to get userId from friends array ,which having status equals to "ACCEPT". ie

 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] 
  • Second Query

After that, I have to make another query on the same collection to get details of each userid returned in the first query. final Query will return details of [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] both userid ie

[
        {
         userid" : "5a88398b9108bf1c48a1a6a9",
         "lastName" : "123",
         "firstName" : "xyz"
         },
       {
         "userid" : "5a88398b9108bf1c48a1a6a91111",
          "lastName" : "456",
           "firstName" : "xyz"
       }
   ]

I have tried so far with

 Users.find ({'_id':5a88389c9108bf1c48a1a6a7,"friends.status":'ACCEPT'}, (error, users) => {})  
   or 


 Users.find ({'_id':5a88389c9108bf1c48a1a6a7, friends: { $elemMatch: { status: 'ACCEPT' } } }, (error, users) => {})
like image 333
Anurag G Avatar asked Feb 28 '18 13:02

Anurag G


People also ask

How do I query nested data in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I filter an array in MongoDB?

Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.


1 Answers

Use the aggregation framework's $map and $filter operators to handle the task. $filter will filter the friends array based on the specified condition that the status should equal "ACCESS" and $map will transform the results from the filtered array to the desired format.

For the second query, append a $lookup pipeline step which does a self-join on the users collection to retrieve the documents which match the ids from the previous pipeline.

Running the following aggregate operation will produce the desired array:

User.aggregate([
    { "$match": { "friends.status": "ACCEPT" } },
    { "$project": {
            "users": {
                "$map": {
                    "input": {
                        "$filter": {
                            "input": "$friends",
                            "as": "el",
                            "cond": { "$eq": ["$$el.status", "ACCEPT"] }
                        }
                    },
                    "as": "item",
                    "in": "$$item.userid"
                }
            }
    } },
    { "$lookup": {  
        "from": "users",
        "as": "users",
        "localField": "users",
        "foreignField": "userid"
    } },
]).exec((err, results) => {
    if (err) throw err;
    console.log(results[0].users); 
});
like image 104
chridam Avatar answered Oct 03 '22 09:10

chridam