使用文档和条件数组加入mongodb
我正在努力创建一个MongoDB查询来使用聚合来执行连接,就像有条件的查询一样。 这是我的意见: “物品”系列:使用文档和条件数组加入mongodb,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我正在努力创建一个MongoDB查询来使用聚合来执行连接,就像有条件的查询一样。 这是我的意见: “物品”系列: { _id : 1 users : [ { userId : 00001, role : "creator" }, { userId : 00002, role : "spectator"
{
_id : 1
users : [
{
userId : 00001,
role : "creator"
},
{
userId : 00002,
role : "spectator"
}
]
}
{
_id : 2
users : [
{
userId : 00002,
role : "creator"
},
{
userId : 00001,
role : "spectator"
}
]
}
{
_id : 00001,
name : "John"
}
{
_id : 00002,
name : "Doe"
}
“用户”集合:
{
_id : 1
users : [
{
userId : 00001,
role : "creator"
},
{
userId : 00002,
role : "spectator"
}
]
}
{
_id : 2
users : [
{
userId : 00002,
role : "creator"
},
{
userId : 00001,
role : "spectator"
}
]
}
{
_id : 00001,
name : "John"
}
{
_id : 00002,
name : "Doe"
}
我想得到一个给定的“东西”的创建者的名字/信息\u id,并得到类似于\u id=1的东西:
{
_id : 00001,
name : "John"
}
到目前为止,我一直在这里:
db.Things.aggregate([
{
$match:{
_id:1
}
},
{
$lookup:{
from:"Users",
localField:"Users.userId",
foreignField:"_id",
as:"usersData"
}
},
{
$unwind : "$usersData"
}
])
提前感谢。
事物$match
和用户\u id
条件角色
解构$unwind
数组用户
$match
角色条件用户
与$lookup
集合用户
从查找结果中获取第一个元素$arrayElemAt
将上述对象替换为root$replaceRoot
第二种方法不使用
$und
阶段
事物$match
和用户\u id
条件角色
要迭代$filter
的循环,请使用
数组并按
创建者角色进行筛选
从上述过滤结果中选择第一个元素$arrayElemAt
与$lookup
集合用户
从查找结果中获取第一个元素$arrayElemAt
将上述对象替换为root$replaceRoot
在
\u id=1
中还有用户id:00002
,你能显示你的预期结果吗。\u id=1
中的userId:00002
在“users”数组中没有创建者的角色,但是观众
在“users”数组中,所以他不是预期结果的一部分。如果users数组中有两个匹配的使用,这是可能的吗?如果是,那么您希望结果如何,在单独的文档中还是在同一文档中。这是不可能的。每个东西
只有一个创建者
,如果我只能有创建者名称和\u id
,那就太完美了,但只要我有名称
,就可以了