I'm developing a Chat application where I'm saving the conversation list in the DB like this;
Conversations Collection:
{
members: [ "123", "456" ]
...rest
}
and User Collection:
{
_id: ObjectId( "123" ), name: "anyone"
},
{
_id: ObjectId( "456" ), name: "someone"
}
I want the result to be like:
{
members: [
{_id: ObjectId( "123" ), name: "anyone"},
{_id: ObjectId( "456" ), name: someone"}
]
}
I know aggregation with lookup is the rescue but can't find a way how to fetch all ids from that member's array because in future it can be 20 to 30 ids. If it is a simple field then I'm able to fetch but with an array, I can't.
CodePudding user response:
You can use a normal .find()
like this:
const members = [
ObjectId('4ed3ede8844f0f351100000c'),
ObjectId('4ed3f117a844e0471100000d'),
ObjectId('4ed3f18132f50c491100000e')
]
const docs = await model.find({
'_id': { $in: members }
}).exec()
CodePudding user response:
You could use the following query to accomplish what you want. You'll need to use $lookup
since you are wanting to gather data from a different collection then the one you are currently querying.
You can check out a live demo here
Database
db={
"conversations": [
{
members: [
123,
456
]
}
],
"users": [
{
"_id": 123,
"name": "foo"
},
{
"_id": 456,
"name": "bar"
}
]
}
Query
db.conversations.aggregate([
{
"$lookup": {
"from": "users",
"localField": "members",
"foreignField": "_id",
"as": "members"
}
},
{
$project: {
_id: 0,
members: 1
}
}
])
Result
[
{
"members": [
{
"_id": 123,
"name": "foo"
},
{
"_id": 456,
"name": "bar"
}
]
}
]