排除$ lookup聚合中的字段

时间:2018-08-21 13:42:37

标签: mongodb mongodb-query aggregation-framework

我正在查询3个集合之间的查询,我想在输出中的任何地方排除_id

我的输出是:

{
    "_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"
    }
}

查询:

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 }}
]) 

在输出中,每个对象都有_id。对于skill列表的示例,每个对象都有_id,我想在任何地方排除_id字段。如何排除?

1 个答案:

答案 0 :(得分:4)

在mongodb 3.6 中,您可以在$project管道内使用投影($lookup)...类似这样的东西

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