我不能在查找管道表达式上使用嵌套字段,以仅获取非空字符串值。
我正在执行一个具有两个查找阶段的聚合查询,其中第二个查找查询取决于第一个查找结果的嵌套字段。我无法真正弄清楚我的代码出了什么问题。
invoice_lines_collection.aggregate([
{'$match':{'customer':'rtv'},
{'$lookup':{
'from':'products',
'localField':'ArticleNumber',
'foreignField':'number',
'as':'article_details'
}
},
{$unwind:{
'path':'$article_details',
'preserveNullAndEmptyArrays': true
}
},
{'$lookup':{
'from':'cutomers',
'let':{'group_id':'$article_details.group._id',
'customer':'$customer'},
'pipeline':{
{'$unwind':'$productgroups'},
{'$match':
{'$expr':
{$and:
['$ne':['$$group_id','2'],
'$eq':
['$productgroups.id','$$group_id'],
'$eq':['$name','$$customer']
],
}
}
}
},
'as':'customer_data'
}
}
])
invoice_lines=[
{
"_id" : ObjectId("5c885d21a202fc001103saf7"),
"ShipmentNumber" : "70727320006714asda4",
"Price" : 179.57,
"customer" : "test"
}
]
products = [
{
"_id" : ObjectId("2cv21eba4bd009f00161153b7"),
"number": "1234",
"group":{
"_id" :'',
"name" : '',
}
},
{
"_id" : ObjectId("5ca1eba4bd009f00161153b7"),
"number" : "2456",
"group" : {
"_id" : ObjectId("5ca29852bd009f00185553e3"),
"name" : "Test group",
}
}
]
customers = [
{
"_id" : ObjectId("5c6fd17a72ef146fcc29c6a1"),
"name" : "test",
"displayName" : "Test",
"productgroups" : [
{
"name" : "Test group",
"id" : ObjectId("5ca29852bd009f00185553e3"),
"markup" : 0.5
},
{
"name" : "Test group 2",
"id" : ObjectId("5ca29852bd009f0888554443"),
"markup" : 3.0
}
]
}
]
我只希望有一个产品组,并且只接受商品所属组的发票行,并获取组详细信息。
当我运行以上代码(转换为PHP语言)时,我得到了
表示表达式的对象必须具有一个字段:{$ ne:[“”,“ $$ group_id”] ...
答案 0 :(得分:0)
我知道了,这是一些语法错误,最后我必须执行$ match阶段才能仅获取发票行包含链接到产品组的产品的结果,现在我的代码看起来像这样:
db.getCollection('invoice_lines').aggregate([
{$match:{'customer':'rtv'}},
{$lookup:{
'from':'products',
'localField':'ArticleNumber',
'foreignField':'number',
'as':'article_details'
}
},
{$unwind:{
'path':'$article_details',
'preserveNullAndEmptyArrays': true
}
},
{$lookup:{
'from':'customers',
'let':{'group_id':'$article_details.group._id',
'customer':'$customer'},
'pipeline':[
{$unwind:'$productgroups'},
{'$match':
{'$expr':
{$and:
[
{$ne:['$$group_id','']},
{$eq:['$productgroups.id','$$group_id']},
{$eq:['$name','$$customer']}
],
}
}
}
],
'as':'customer_data'
}
},
{$match:{'customer_data':{$exists: true, $not: {$size: 0}}}}