2

my db collection is like

 {  "_id" : "57f4c1323eb5c694041ghea3",
 "example" : [ 
    {
        "exId" : "57f4c0d43eb5c694041fdebd",
        "_id" : ObjectId("57f4c1323eb5c694041fded2"),
        "projects" : [ 
            "57f4c1303eb5c694041fdec6"
        ]
    }, 
    {
        "exId" : "57f24ee56da92f9c19b0efd4",
        "_id" : ObjectId("57f4cfa93eb5c694041fdf4c"),
        "projects" : [ 
            "57f4cfa83eb5c694041fdf45"
        ]
    }, 
    {
        "exId" : "57f24ec16da92f9c19b0efcd",
        "_id" : ObjectId("580864867a36f5bc1058c2c8"),
        "projects" : [ 
            "580864837a36f5bc1058c2a9", 
            "57f4c1303eb5c694041fdec6"
        ]
    }
],

I need to get output as

"example": [
{
  "exId": "57f24ee56da92f9c19b0efd4",
  "_id": "57f4cfa93eb5c694041fdf4c",
  "projects": [
    "57f4cfa83eb5c694041fdf45"
  ]
},
{
      "exId" : "57f24ec16da92f9c19b0efcd",
      "_id" : ObjectId("580864867a36f5bc1058c2c8"),
      "projects" : [ 
          "580864837a36f5bc1058c2a9", 
          "57f4c1303eb5c694041fdec6"
      ]
  }
 ]
 }

where my query is

     db.userDb.findOne({ '_id': req.params.userId }, { example: { $elemMatch: { exId: { $in: accIds } } } })

and accIds is an array contains values "57f24ec16da92f9c19b0efcd", "57f24ee56da92f9c19b0efd4", "57f24fa26da92f9c19b0f005"

but my ouput is

"example": [
{
  "exId": "57f24ee56da92f9c19b0efd4",
  "_id": "57f4cfa93eb5c694041fdf4c",
  "projects": [
    "57f4cfa83eb5c694041fdf45"
  ]
}

],

any help is appreciated

4
  • not 'acc' array name is 'accIds' Commented Jan 5, 2017 at 10:18
  • 1
    edit your question rather than commenting Commented Jan 5, 2017 at 10:19
  • 1
    Is example the topmost element? If yes, findOne could be the reason why you get exactly 1 result. Commented Jan 5, 2017 at 10:28
  • No it is not the topmost one Commented Jan 5, 2017 at 10:31

1 Answer 1

1
db.collection.aggregate([
            { $unwind: '$example' },
            { $unwind: '$example.projects' },
            { $match: { 'example.exId': { $in: accIds} } },
            { $group: { _id: null, projectList: { $addToSet: '$example.projects'  } } },
        ])

Hope this will work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.