exclude fields in $lookup aggregation

2019-01-08 02:11发布

问题:

I am querying between 3 collections I want to exclude _id everywhere in output

My output is:

{
    "_id" : ObjectId("5b6aed5f9bcdb5d4ae64aef5"),
    "userID" : "1",
    "skills" : [ 
        {
            "_id" : ObjectId("5b766b5f1365a4940bb6050f"),
            "skillID" : "javaid",
            "skillname" : "जावा",
            "languageID" : "hindiid"
        }, 
        {
            "_id" : ObjectId("5b766b8c1365a4940bb60535"),
            "skillID" : "pythonid",
            "skillname" : "पायथन",
            "languageID" : "hindiid"
        }
    ],

    "gender" : {
        "_id" : ObjectId("5b7687cd2a2329043e2383d5"),
        "genderID" : "femaleid",
        "gendername" : "महिला",
        "languageID" : "hindiid"
    }
}

Query:

db.User.aggregate([
  { "$match": { "userID":"1" }},
  { "$lookup":{
    "from": "Skill",
    "pipeline": [
      { "$match": { "languageID": "hindiid", "skillID": { "$in": [ "javaid","pythonid" ] }}},
    ],
    "as": "skills"
  }},
  { "$lookup": {
    "from": "Gender",
    "pipeline": [
      { "$match": { "languageID": "hindiid", "genderID" : "femaleid" }},
    ],
    "as": "gender"
  }},
  { "$unwind": { "path": "$gender", "preserveNullAndEmptyArrays": true }},
  { "$project": { "userID": 1, "skills": 1, "gender": 1 }}
]) 

In output for every object has _id.Example for skill list every object has _id i want exclude _id field every where. How I can exclude?

回答1:

In mongodb 3.6 you can use projection ($project) inside $lookup pipeline... Something like this

db.User.aggregate([
  { "$match": { "userID":"1" }},
  { "$lookup":{
    "from": "Skill",
    "pipeline": [
      { "$match": { "languageID": "hindiid", "skillID": { "$in": [ "javaid","pythonid" ] }}},
      { "$project": { "_id": 0 }}
    ],
    "as": "skills"
  }}
])