首页 > 解决方案 > Mongodb 查找所有并更新除一个以外的所有内容

问题描述

所以我有这个数据库查找

    const channelLinkId = "123456"

    location = await Locations.find({
      services: {
        $elemMatch: {
          credentials: channelLinkId,

        },
      },
    });

这就是我从那个 db 中得到的结果,它查找了一个 db 对象数组。

[
  {
    name: "test",
    services: {
    credentials: "123456"
    }
}
  {
    name: "test1",
    services: {
    credentials: "123456"
    }
},
  {
    name: "test1",
    services: {
    credentials: "123456"
    }
  }
]

我想要从这个数据库查找中得到的结果是让这个数组的第二个和第三个值的凭据为空。

[
  {
    name: "test",
    services: {
    credentials: "123456"
    }
}
  {
    name: "test1",
    services: {
    credentials: ""
    }
},
  {
    name: "test1",
    services: {
    credentials: ""
    }
  }
]

标签: javascriptnode.jsmongodbexpress

解决方案


单个更新查询是不可能的,

  • 仅在不需要其他字段时使用finOne()并选择一个文档_id
const channelLinkId = "123456"
let location = await Locations.findOne({ "services.credentials": channelLinkId }, { _id: 1 });
  • 更新不在上面找到的文档的其他文档的凭据
await Locations.updateMany(
  { _id: { $ne: location._id }, "services.credentials": channelLinkId },
  { $set: { "services.credentials": "" } }
);

推荐阅读