How to filter and map array of documents in MongoDB query?

后端 未结 1 1897
死守一世寂寞
死守一世寂寞 2021-01-03 07:00

So I\'ve got these documents in my people collection:

{
        \"_id\" : ObjectId(\"595c0630939a8ae59053a9c3\"),
        \"name\" : \"John Smith\",
                 


        
1条回答
  •  囚心锁ツ
    2021-01-03 07:31

    You can wrap the $filter expression inside $map to map the output values.

    db.people.aggregate([
      {
        "$project": {
          "name": 1,
          "age": 1,
          "hobbies": {
            "$map": {
              "input": {
                "$filter": {
                  "input": "$hobbies",
                  "as": "hobbyf",
                  "cond": "$$hobbyf.regular"
                }
              },
              "as": "hobbym",
              "in": {
                "name": "$$hobbym.name",
                "type": "$$hobbym.type"
              }
            }
          }
        }
      }
    ])
    

    0 讨论(0)
提交回复
热议问题