简体   繁体   中英

Lookup with condition mongoDb

I have a collection myCollection with array of members :

{
   name : String,
   members: [{status : Number, memberId : {type: Schema.Types.ObjectId, ref: 'members'}]
}

and a collection members

{
    firstname : String,
    lastname  : String
}

and i have this data

"_id" : ObjectId("5e83791eb49ab07a48e0282b")
   "members" : [ 
        {
            "status" : 1,
            "_id" : ObjectId("5e83791eb49ab07a48e0282c"),
            "memberId" : ObjectId("5e7dbf5b257e6b18a62f2da9")
        }, 
        {
            "status" : 2,
            "_id" : ObjectId("5e837944b49ab07a48e0282d"),
            "memberId" : ObjectId("5e7de2dbe027f43adf678db8")
        }
    ],

I want to select only members of status 1 and make a lookup for getting data of members, I tried this but it returns all members status (1 and 2), how can I make the query, thank you.

db.getCollection('myCollection').aggregate([
    {$match: {_id: ObjectId("5e83791eb49ab07a48e0282b")}},
           { "$lookup": {
                "from": "members",
                "let": { "ar": "$members.memberId" , "ar2": "$members.status" },


    "pipeline": [
      { "$match": {
        "$expr": {
          "$cond": [
            { "$in": ["$_id", "$$ar"] },

          {},
           { "$eq": [1, "$$ar2"] }, 
          ]
        }
      }}
    ],
    "as": "Member"
  }},
         {   $project: {

                 "Member._id" : 1,
                "Member.firstname" : 1,
                "Member.lastname" : 1
            }

        }

    ])

If you only want data of status 1 then you should do that by filtering out the results first and then use $lookup

$match:{
    "members.status":1
}

I don't know why do you need _id in $match, but the above mentioned $match object will work to filter out the results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM