简体   繁体   中英

MongoDb query on two collections

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM