【发布时间】:2021-09-30 15:25:44
【问题描述】:
我试图在查找运算符之后过滤数据。我没有从我的查询中得到预期的行为。
我的网关收藏是
{ "_id" : "18001887", "mac_id" : "18001887", group_id: "0" }
{ "_id" : "18001888", "mac_id" : "18001888", group_id: "1" }
{ "_id" : "18001889", "mac_id" : "18001889", group_id: "0" }
我的命令集合是
{
"_id" : ObjectId("615581dcb9ebca6c37eb39e4"),
"org_id" : 0,
"mac_id" : "18001887",
"config" : {
"user_info" : [
{
"user_id" : 1,
"user_pwd" : "123456",
"mapped_id" : 1
},
{
"user_id" : 2,
"user_pwd" : "123123",
"mapped_id" : 3
}
]
}
}
{
"_id" : ObjectId("615581dcb9ebca6c37eb39e4"),
"org_id" : 0,
"mac_id" : "18001889",
"config" : {
"slave_id" : 1
}
}
我想获取 group_id = 0 和 "config.user_info.mapped_id" = 1 的网关命令。 我写了下面的查询,但它似乎不起作用
gateway_model.aggregate([
{
$match: {
group_id: "0"
},
},
{
$project: {
_id: 0,
mac_id: 1
}
},
{
$lookup: {
from: "commands",
localField: "mac_id",
foreignField: "mac_id",
as: "childs"
}
},
{
$project: {
mac_id: 1,
childs: {
$filter: {
"input": "$childs",
"as": "child",
"cond": {"$eq": ["$$child.config.user_info.mapped_id", 1]},
}
}
}
}
])
以上查询返回 group_id 为 0 且 childs 为空数组的网关。
【问题讨论】:
-
这就是它应该如何工作的。
$filter运算符将返回一个数组,其中包含与cond匹配的任何元素。如果没有匹配,则数组将为空。 -
但是在这种情况下有一个
child.config.user_info.mapped_id = 1。检查命令集合示例。我使用的是相同的数据。
标签: mongodb mongodb-query aggregation-framework