如何从 MongoDB 中的数组中查找特定对象

How to find specific object from array in MongoDB

假设我有这个 MongoDB 文档:

{
  "_id": {
    "$oid": "628f739398580cae9c21b44f"
  },
  "place":"Amsterdam",
  "events": [
    {
      "eventName": "Event one",
      "eventText": "Event",
      "eventDate": "010101"
      "host":"Bob"
    },
    {
      "eventName": "E2",
      "eventText": "e2",
      "eventDate": "020202"
      "host":"John"
    }
  ]
}

{
  "_id": {
    "$oid": "628f739398580cae9c21b44f"
  },
  "place":"London",
  "events": [
    {
      "eventName": "e3",
      "eventText": "e3",
      "eventDate": "010101",
      "host":"Bob"
    }
  ]
}

我想获取 Bob 主持的事件数组块,我该怎么做?我试过像这样使用 $elemSelector

const result = await mongoDatabase
      .collection("temp")
      .find({ events: { $elemMatch: { eventName: "E2" } } })
      .toArray();

    console.log(JSON.stringify({ result }));

但它只是 returns 所有与所选地点相同的活动,在本例中为阿姆斯特丹。

想要的结果:

{
  "eventName": "Event one",
  "eventText": "Event",
  "eventDate": "010101"
  "host":"Bob"
},
{
  "eventName": "e3",
  "eventText": "e3",
  "eventDate": "010101",
  "host":"Bob"
}

试试这个。

db.getCollection('events_or_whatever_u_').find({'_id': ObjectId('xxxxx')})

看看这个

db.collection.aggregate({
  $unwind: "$events"
},
{
  $match: {
    "events.host": "Bob"
  }
},
{
  "$project": {
    "events": 1,
    "_id": 0
  }
},
{
  "$replaceRoot": {
    "newRoot": "$events"
  }
})

您可以在此处尝试更多测试数据:https://mongoplayground.net/p/A1UbZdZgZmr

您可以通过简单的流水线阶段实现

db.collection.aggregate([
  {
    "$match": {//Match
      "events.host": "Bob"
    }
  },
  {
    "$project": {
      "e": {
        "$filter": {//Filter matching elements
          "input": "$events",
          "as": "event",
          "cond": {
            "$eq": [
              "$$event.host",
              "Bob"
            ]
          }
        }
      }
    }
  }
])

Playground

以下结构可以通过在 MongoDB 中使用 projection query 来实现,上面的一个清晰的解决方案可以是这个

 db.collection("temp").find({ "events":{ $elemMatch:{ "eventName":"e3" }  } }, {"events":1,"_id":0})