我有这两个集合,我需要使用第一个集合的参数从其中一个集合进行查询
收藏范例:
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"
}
我需要从集合1获取ID和“ lastDate”,并使用它在集合2上进行查询
对不起,不好的解释告诉您是否需要更多信息或其他信息
等效的SQL
SELECT * FROM collection2
WHERE site IN (SELECT id FROM collection1) and
date IN (SELECT lastDate FROM collection1);
答案 0 :(得分:1)
let params = {_id:1}
let data = await Collection1.aggregate([
{$match:params},
{
$lookup: {
from: "collection2",
localField: "$collection1datefield",
foreignField: "$collection2datefield",
as: "collection2Object"
}
}
])
答案 1 :(得分:0)
如果您已完成对第一个集合的引用,则可以使用简单查询,即
const query = await Collection1.findOne({id: req.params.id}).populate('site lastDate');
答案 2 :(得分:0)
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,
},
},
},
},
]);
我邀请您阅读有关Aggregation
的更多信息