MongoDB 数组内查询

MongoDB query inside an array

我想使用这个 mongoDB 合集:

[
  {
    "_id": {
      "$oid": "627c4eb87e7c2b8ba510ac4c"
    },
    "Contact": [
      {
        "name": "ABC",
        "phone": 5501234,
        "mail": "abc@mail.com"
      },
      {
        "name": "DEF",
        "phone": 6001234,
        "mail": "def@mail.com"
      }
    ],
    "nomatter": "trash"
  }
]

仅搜索 {"name":"ABC"} 和 return {"mail":"abc@mail.com"}

可以用find还是必须用aggregate?

试试这个:

db.collection.aggregate([
  { $match: { "Contact.name": "ABC" } },
  {
    $project: {
      Contact: {
        $filter: {
          input: "$Contact",
          cond: { $eq: [ "$$this.name", "ABC" ] }
        }
      }
    }
  },
  { "$replaceWith": { mail: { $first: "$Contact.mail" } } }
])

Mongo Playground