如何过滤 mongodb 中的数组元素

How to filter elements of array in mongodb

我在 mongodb 中有一个文档:

{
    "company": "npcompany",
    "department": [
          {
           "name": "it",
           "employeeIds": [
               "emp1",
               "emp2",
               "emp3"
           ]
         },
         {
           "name": "economy",
           "employeeIds": [
               "emp1",
               "emp3",
               "emp4"
           ]
         }
    ]
}

我想找到“emp4”。在这种情况下,我只想获取“经济”部门数据。如果我找到“emp1”,那么我想获得“npcompany”和“economy”数据。我如何在 mongodb(或 pymongo)中做到这一点?

play

db.collection.aggregate([ //As you need to fetch all matching array elements, reshape them
  {
    $unwind: "$department"
  },
  {
    "$match": {//look for match
      "department.employeeIds": "emp4"
    }
  },
  {
    $group: {//regroup them
      "_id": "$_id",
      data: {
        "$push": "$$ROOT"
      }
    }
  }
])