首页 > 解决方案 > 如何取消选择数组 MongoDB 中的一个对象?

问题描述

在我的情况下,我只需要我的结果,但我的数组中没有我的 objectID。

这是我的方法:

return Room.findOne(
    {
      _id: idRoom,
      participants: {$elemMatch: {$ne: this.currentUser.profile}},
    },
    {
      'participants.$': 1,
    }
  )

使用 elementMatch,问题是当您找到对象时,只返回第一个对象。

这是我的结果:

"result": {
    "_id": "5da5e77f51e08708b79565e8",
    "participants": [
       "5da4d5b40cc94f04a7aaad40"
    ],

这是我需要的真正结果

"result": {
    "_id": "5da5e77f51e08708b79565e8",
    "participants": [
       "5da4d5b40cc94f04a7aaad40"
       "fwnert9248yrhnqwid13982r" // I have another participants
    ],

我的模型是这样的:

const RoomSchema = new Schema({
  participants: [{type: Schema.Types.ObjectId,ref: 'Profile'}],
  ...
}, options)

由于其他原因,我不能使用聚合,如果你有解决方案,谢谢

标签: mongodb

解决方案


因此,我认为您正在尝试使用该findOne()方法在 mongo 中塑造结果集,并且聚合管道框架的任何使用都是不可能的,并且由于其他原因不可用。

我不确定这是可能的。我相信您需要执行多个步骤才能达到您想要的结果。如果您可以使用聚合管道框架,这里是一个适合所需结果的管道(我相信)......

db.Room.aggregate(
    [
        {
            "$match": { _id: ObjectId(idRoom)}
        },
        {
            $project: {
                "participants": {
                    $filter: {
                        input: "$participants",
                        as: "participant",
                        cond: {$ne: ["$$participant", this.currentUser.profile] }
                    }
                }
            }
        }
    ]
)

...但是如果您不能使用聚合管道,那么这里是一个 mongoshell 脚本,它分几个步骤完成任务。策略是通过 _id 捕获整个文档,然后从数组中删除数据元素,然后回显结果......

var document = db.Room.findOne( { _id: ObjectId("5da64a62cd63abf99d11f210") } );
document.participants.splice(document.participants.indexOf("5da4d5b40cc94f04a7aaad40"), 1);
document;

推荐阅读