Mongodb 查找中的映射嵌套集合
我有两个收藏:物品和佣金Mongodb 查找中的映射嵌套集合,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有两个收藏:物品和佣金 // collection items { _id: ObjectId("5d2b9e2da676e50cb9d061fe"), name: 'some name' } // collection commisions { _id: ObjectId("5d2cb8ad7240251917b18c03"), items: [ { item: ObjectId("5d2b9e2da676e50cb9d
// collection items
{
_id: ObjectId("5d2b9e2da676e50cb9d061fe"),
name: 'some name'
}
// collection commisions
{
_id: ObjectId("5d2cb8ad7240251917b18c03"),
items: [
{
item: ObjectId("5d2b9e2da676e50cb9d061fe")
}
]
}
现在使用聚合,我需要找到具有佣金计数的项目(在它们出现的佣金数量中)。我正在尝试:
db.getCollection('items').aggregate([{
$match: {
_id: ObjectId("5d2b9e2da676e50cb9d061fe")
}
}, {
$lookup: {
from: 'commisions',
let: {
item: '$_id',
items: {
$map: {
input: '$items',
as: 'i',
in: '$$i.item',
}
}
},
pipeline: [{
$match: {
$expr: {
$in: ['$item', '$items']
}
}
}],
as: 'commisions'
}
},
{
$project: {
commisions: 1,
commisionsSize: { $size: '$commisions' }
}
},
{
$limit: 100
}
])
但当我尝试运行此查询时,我得到:
“errmsg”:“$in需要一个数组作为第二个参数,发现:缺少”
问题是
commission.items
不是一个平面数组,而是嵌套的。我想您只是对$lookup
语法有点困惑,特别是您在let
部分中定义的变量应该属于当前集合,而不是您要从中查找的集合
试试这个:
db.getCollection('items').aggregate([
{
$match: {
_id: ObjectId("5d2b9e2da676e50cb9d061fe")
}
},
{
$lookup: {
from: 'commisions',
let: {item: '$_id'},
pipeline: [
{
$match: {
$expr: {
$in: [
'$$item',
{
$map: {
input: '$items',
as: 'i',
in: '$$i.item',
}
}
]
}
}
}],
as: 'commisions'
}
},
{
$project: {
commisions: 1,
commisionsSize: {$size: '$commisions'}
}
},
{
$limit: 100
}
])
美好的我想我把
'$$item'