在MongoDB的$lookup函数中使用字段值 [英] Use Field values in $lookup function in MongoDB
本文介绍了在MongoDB的$lookup函数中使用字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前我面临一个问题,即我希望基于变量联接Mongo中的集合,因为数据存储在不同的集合中。
我的数据集将如下所示
{
_id:5e424331134cea013014ea9e0,
process:"Process1",
event:"Event1",
collection:"Collection1",
Date:"2020-02-11",
},
{
_id:5e424135151cea32114ea9e0,
process:"Process2",
event:"Event2",
collection:"Collection2",
Date:"2020-02-11",
}
我需要从中获取数据的集合维护在$collection
字段的值中。
这些集合如下所示:
集合1:
{
_id:5e63636636cea32114ea9e0,
item:81740147,
value:2,
Date:"2020-02-11",
}
集合2:
{
_id:5e63636636cea32114ea9e0,
user:testuser,
age:3,
Date:"2020-02-11",
}
我希望在聚合管道中实现的功能是基于集合名称联接我的文档。
我已经尝试的内容:
{
$lookup: {
from: '$collection',
localField: 'Date',
foreignField: 'Date',
as: 'join'
}
}
这对我不起作用。 也许你有不同的想法。
请记住,我只能使用聚合框架来解决问题,而不能使用MongoDB的CLI。
推荐答案
将其更改为如下所示
{
$lookup: {
from: 'collectionname', // the name you specified when creating your model
localField: 'Date',
foreignField: 'Date',
as: 'join'
}
}
它必须与您创建模型时使用的相同,否则将不起作用
如果您的集合名称是动态的,
您始终可以在那里使用变量
就像你可以做这样的事情
var coll_name = 'collectionname';
{
$lookup: {
from: coll_name,
localField: 'Date',
foreignField: 'Date',
as: 'join'
}
}
现在,您可以将此动态集合名称从任何位置传递到您的函数/API
这篇关于在MongoDB的$lookup函数中使用字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文