如何使用mongodb删除基于_id的数组中的嵌套文档

b5lpy0ml  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(140)

如果createdEventId等于我传递给它的id,我想从名为createdEvents的对象数组中提取一个嵌套对象。

我的javascript查询如下所示:

db.collection("users").updateOne({ _id: userId }, { $pull: { createdEvents: { "createdEvents.createdEventId": eventId } } })

我还尝试了以下方法,结果相同

const deleteUserCreatedEvent = await db.collection("users").updateOne({ _id: userId }, { $pull: { createdEvents: { "createdEventId": eventId } } })

我的文档如下所示:

{
  "_id": {
    "$oid": "63669a7fadb92eac2df57fc9"
  },
  "email": "wakywayne80@gmail.com",
  "emailVerified": {
    "$date": {
      "$numberLong": "1667668607915"
    }
  },
  "createdEvents": [
    {
      "createdEventName": "pushevent",
      "createdEventDate": {
        "$date": {
          "$numberLong": "1667913330000"
        }
      },
      "createdEventDescription": "It's gonnam be a good one",
      "createdEventWeights": [],
      "createdEventId": {
        "$oid": "6368222391d6001d3d2986e2"
      }
    }
  ]
}

当我运行上面的代码时,返回true,就好像查询成功了,但是文档仍然在数据库中。

m1m5dgzv

m1m5dgzv1#

确保使用新的ObjectId(theIdString),然后执行以下查询:

updateOne({_id: new ObjectId(userId)}, {$pull: {createdEvents:{createdEventId:new ObjectId(eventId) }}})

相关问题