即使$ lookup失败,也让聚合继续

时间:2018-01-25 14:09:10

标签: mongodb aggregation-framework

我有一个很长的聚合,在这个聚合内部就是这个$ lookup:

{ '$lookup': { from: 'users', localField: 'user', foreignField: '_id', as: 'users' } },
{ '$unwind': '$users' },

问题是如果它没有在用户中找到用户,那么它将跳过整个记录而不返回$ project中的任何内容。

有办法做什么" $ lookup,如果你失败,只要显示主要记录" ?

以下是完整的聚合:

db.booking.aggregate([ 
    { '$match': 
        { 
            status: { '$in': [ 0, 1, 2, 3, 4, 5, 6, 9 ] }, 
            '$or': [ 
                { checkin: { '$gte': 1516320000 }, checkout: { '$lte': 1521417600 } }, 
                { checkin: { '$lt': 1516320000 }, checkout: { '$gt': 1521417600 } }, 
                { checkin: { '$lt': 1516320000 }, checkout: { '$gt': 1516320000 } }, 
                { checkin: { '$lt': 1521417600 }, checkout: { '$gt': 1521417600 } } 
            ] 
        }
    }, 
    { '$sort': { checkin: 1 } }, 
    { '$lookup': { from: 'users', localField: 'user', foreignField: '_id', as: 'users' } }, { '$unwind': '$users' }, 
    { '$project': { _id: 1, property: 1, user: 1, name: '$users.name', country: '$users.country', checkin: 1, checkout: 1, priceNight: 1, status: 1, source: 1 } } 
], {})

0 个答案:

没有答案