Reputation: 246
I have this two Collections that I use, I need to query from one of the collection using params from the first collection
Collection expamples:
Collection 1 :{
id: 1234,
lastDate : "2020-09-10T08:30:14.960+00:00"
}
Collection 2 :{
site : 1234,
date : "2020-09-10T08:30:14.960+00:00"
}
I need to get the id and "lastDate" from Collection 1 and use it to query on Collection 2
sorry for bad explanation tell if need more info or anything
ADDED SQL equivalent
SELECT * FROM collection2
WHERE site IN (SELECT id FROM collection1) and
date IN (SELECT lastDate FROM collection1);
Upvotes: 0
Views: 159
Reputation: 328
db.FIRST_COLLECTION.aggregate([
{
$lookup: {
from: "FIRST_COLLECTION",
localField: "id", // local field of first collection
foreignField: "site", // foreign field at second collection
as: "liste",
},
},
{ $unwind: "$liste" },
{
$group: {
_id: "$site",
data: {
$addToSet: {
site: $site,
date: $date,
},
},
},
},
]);
I invite you to read more about Aggregation
Upvotes: 0
Reputation: 4040
let params = {_id:1}
let data = await Collection1.aggregate([
{$match:params},
{
$lookup: {
from: "collection2",
localField: "$collection1datefield",
foreignField: "$collection2datefield",
as: "collection2Object"
}
}
])
Upvotes: 1
Reputation: 95
If you have done referencing into the first collection then you can use simple query i.e
const query = await Collection1.findOne({id: req.params.id}).populate('site lastDate');
Upvotes: 0