2

I have two collection as below First collection is Users:

{
"userid":123,
"name":"abc",
"age":20,
"status":"Active"
}
{
"userid":345
"name":"cde"
"age":25,
"status":"Active"
}

second collection is userComment:

{
"userid":123,
"commnet":"Mongodb rocks"
}

can anyone please help me writing the query to fetch the users with "Active" status alongwith a flag that will tell me whether user has any comment or not So the o/p should be

{
"userid":123,
"name":"abc",
"age":20,
"status":"Active"
"userscommentFlag":"Y"**
}
{
"userid":345
"name":"cde"
"age":25,
"status":"Active"
"userscommentFlag":"N"
}

Thanks.

felipsmartins
  • 13,269
  • 4
  • 48
  • 56
Ranjit
  • 29
  • 1
  • Can you post the scheme from the models ? – Alvaro Silvino May 30 '16 at 02:39
  • If you are using mongo 3.2 latest version, you can use `$lookup` in the aggregation pipeline to join/populate fields from other collection. See https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ – Rudra May 30 '16 at 04:52
  • Possible duplicate of [MongoDB query multiple collections at once](https://stackoverflow.com/questions/6502541/mongodb-query-multiple-collections-at-once) – Guilherme Ferreira Sep 23 '19 at 18:25

1 Answers1

1

Using $lookup in aggregation pipeline this can be done as:

db.users.aggregate(
[{$lookup:
 {from:"userComment", localField:"userid", foreignField: "userid", as: "comments"
}}])

Note: $lookup is supported in mongodb 3.2

Atish
  • 4,277
  • 2
  • 24
  • 32