mongodb中的聚合$unvent,$lookup不起作用



这是我在mongo shell 中构造的查询

db.vendormasters.aggregate([
{ 
'$match': {
status: 'active',
}
},
{ '$unwind': '$mappedToDealers'},
{
$lookup: {
from: "orders",
let: {
vendorId: "$_id",dealerId:'$mappedToDealers'
},
pipeline: [
{
$match: {
$and: [
{
$eq: [
"$vendorId",
"$$vendorId"
]
},
{
$eq: [
"$dealerId",
"$$dealerId"
]
}
]
}
}
], as: "orders"
}
},
{ '$unwind': '$orders' },
}]).pretty()

**我在shell中得到的错误消息是**

E  QUERY    [js] Error: command failed: {
"ok" : 0,
"errmsg" : "unknown top level operator: $eq",
"code" : 2,
"codeName" : "BadValue"
} : aggregate failed :
my collection structure is 
//////collection 1 : vendorMasters///////////
{
"_id" : ObjectId("5e5642e32500b8273cbde3ac"),
"mappedToDealers" : [
ObjectId("5e1d82156a67173cb877f67d"),
ObjectId("5e5906dfc749dc4498033f7f")
],
"phoneNo" : 6#7159###,
"name" : "addedVendor8",
"address" : "Address6",
}
//////collection 2: orders///////////
{
"_id" : ObjectId("5e3a710af2657521e8c5668a"),
"date" : ISODate("2020-02-11T18:30:00Z"),
"order" : [
{
"_id" : ObjectId("5e3a710af2657521e8c5668c"),
"punchCount" : "###1",
"leavecCount" : 5,
},
{
"_id" : ObjectId("5e3a710af2657521e8c5668b"),
"punchCount" : "###1",
"leavecCount" : 5,
}
],
"vendorId" : ObjectId("5e5642e32500b8273cbde3ac"),
"dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
}
{
"_id" : ObjectId("5e3a710af2657521e8c5668a"),
"date" : ISODate("2020-02-11T18:30:00Z"),
"order" : [
{
"_id" : ObjectId("5e3a710af2657521e8c5668c"),
"punchCount" : "###1",
"leavecCount" : 6,
},
{
"_id" : ObjectId("5e3a710af2657521e8c5668b"),
"punchCount" : "###1",
"leavecCount" : 2,
}
],
"vendorId" : ObjectId("5e5642e32500b8273cbde3ac"),
"dealerId" : ObjectId("5e5906dfc749dc4498033f7f"),
}

注意:文档中可能有不同的vendorId和不同的dealerId。如果没有匹配,那么我应该返回一个空数组,在我的查询中指出问题所在。我的目标是从订单集合中找出所有具有匹配vendorId&dealerId如果不匹配,则返回空数组

$match条件只包含一个逻辑表达式:

$match: { $and: [...] }

但是,它必须包含查询。试试这个:

$match: { $expr: { $and: [...] } }

最新更新