MongoDB聚合$或与$ elemMatch一起使用,在$ lookup管道中包含$ expr [英] MongoDB aggregation $or with $elemMatch, $expr inside $lookup pipeline
本文介绍了MongoDB聚合$或与$ elemMatch一起使用,在$ lookup管道中包含$ expr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个收藏集:
用户集合:
{
_id: ObjectId
}
多多收藏集:
{
_id: ObjectId
fieldA: {_id: ObjectId}
fieldB: [{_id: ObjectId}, {_id: ObjectId}]
}
并且我正在尝试加入 fieldA的ID 或 fieldB的ID 之一与用户的ID 匹配的A集合的元素以下聚合:
And I'm trying to join the element of A collection which fieldA's id OR one of fieldB's id is matching with user's id with following aggregation :
db.users.aggregate([
{
$lookup: {
from: "Toto",
let: { "user_id": "$_id" },
as: "fcollection",
pipeline: [
{ $match:
{$or:[
{"fieldB": {$elemMatch: {"_id": "$$user_id"}}},
{$expr: {$eq :["$fieldA._id", "$$user_id"]}}
]}
}
]
}
])
但是在输出中,我只是获取文档,其中fieldA的ID匹配,但没有fieldB的ID.我在做什么错了?
But in the output I'm just getting the document's where fieldA's id is matching but none of the fieldB's. What am I doing wrong?
推荐答案
您需要使用 $ in 聚合管道运算符,用于检查数组中是否存在元素:
You need to use $in aggregation pipeline operator to check an element exists in an array :
db.users.aggregate([
{
$lookup: {
from: "Toto",
let: {
"user_id": "$_id"
},
as: "fcollection",
pipeline: [
{
$match: {
$or: [
{
$expr: {
$in: [
"$$user_id",
"$fieldB._id"
]
}
},
{
$expr: {
$eq: [
"$fieldA._id",
"$$user_id"
]
}
}
]
}
}
]
}
}
])
这篇关于MongoDB聚合$或与$ elemMatch一起使用,在$ lookup管道中包含$ expr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文