I have a collection called "User". I'm passing userid to get the record. In addition to that i also need additional 10 last updatedAt(DateTime) record excluding the userid record but added together. So, total returned result will be 11 in this case. Is that possible using same query? I tried using Or and lookup but can't make it work as expected. Any help is appreciated.
User collection:
[{
"id" : "123456",
"name" : "foo",
"addressIds" : [ObjectId(234567)]
} ,
"id" : "345678",
"name" : "bar",
"addressIds" : [ObjectId(678565), ObjectId(567456)]
}]
Address collection:
[{
"_id":"234567",
"district" : "district1",
"pincode" : "568923",
},
{
"_id":"678565",
"district" : "district2",
"pincode" : "568924",
},
{
"_id":"567456",
"district" : "district3",
"pincode" : "568925",
}]
Using facets, i have the User and the addressIds. Can i have the actual documents for AddressIds in User?
Edit:
You can use $facet
, like this:
db.collection.aggregate([
{$sort: {date: -1}},
{$facet: {
byTate: [{$limit: 10}],
byUser: [{$match: {userId: 455845}}]
}
},
{$project: {
byDate: {
$filter: {
input: "$byDate",
as: "item",
cond: {$ne: ["$$item",{"$arrayElemAt": ["$byUser", 0]}]}
}
},
byUser: 1,
}
},
{
$project: {
byDate: {$slice: ["$byDate", 10]},
byUser: 1
}
}
])
You can see it works on the playground .
Switch between userId: 455845 / 455845 to see both cases.