2017-11-25 67 views
0

進行查找是否有可能在MongoDB中進行查找,但只在一定的條件?我需要的事件構成了我的MongoDB,只有當事件被某些用戶添加相關的賭注 - 我想賭添加到收藏。如何在一定的條件

首先,我用匹配操作符和$查找,以獲得有關事件的賭注,但問題是我需要定義第二個條件 - 賭注的用戶標識必須是相同的外部參數(用戶ID)的值。

然後我需要添加只有一個結果,不是一個集合 - 這就是爲什麼我用$項目。請幫忙。

我的代碼放在這裏:

  db.collection('events').aggregate([ 
       { 
        $match: { 
         'isDeleted': false, 
         'leagueId': ObjectID(leagueId) 
        } 
       }, 
       { 
        $lookup: { 
         from: "bets", 
         localField: "_id", 
         foreignField: "eventId", 
         as: "bets" 
        }, 
       }, 
       { 
        $project: { 
         _id: true, 
         home: true, 
         guest: true, 
         description: true, 
         result: true, 
         resultHome: true, 
         resultGuest: true, 
         startDate: true, 
         type: true, 
         specialPoints: true, 
         leagueStage: true, 
         createdDate: true, 
         updatedDate: true, 
         isDeleted: true, 
         isCalculated: true, 
         leagueId: true, 
         bet: { "$arrayElemAt": [ "$bets", 0 ] } 
       } 
      } 

回答

1

不,你不能在$lookup的條件。但是你可以做以下事情。 查找後,你有bets陣列。您可以使用$unwind。 這樣你就有了一個陣列的平面表示。這意味着如果您有兩個數組條目的文檔,那麼將創建2個具有相同字段和名稱的文檔,只有數組會有所不同。

然後你就可以再次使用$match過濾出你想要的。然後,你就不需要使用$project,除非你想修改您的文檔。

所以你聚集管道將是這個樣子:

db.getCollection('events').aggregate([{ 
     $match: { 
      'isDeleted': false, 
      'leagueId': ObjectID(leagueId) 
     } 
    }, 
    { 
     $lookup: { 
      from: "bets", 
      localField: "_id", 
      foreignField: "eventId", 
      as: "bets" 
     }, 
    }, 
    { 
     $unwind: "$bets" 
    }, 
    { 
     // match here again to only get the bet you need 
    } 
]) 

希望它能幫助。