javascript - 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: ""
}
}
]
解决方案
单个更新查询是不可能的,
- 仅在不需要其他字段时使用
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": "" } }
);
推荐阅读
- java - 找不到参数的方法 jaxws() [com.sun.xml.ws:jaxws-tools:2.1.4]
- c# - 如何改变文化?
- jquery - 使用 jQuery 检索嵌套的 JSON 数据
- javascript - 在不改变位置的情况下缩放 svg 组
- bash - Jenkins 如何在我的远程 shell 脚本中传递 GIT_BRANCH 参数
- c# - 使用 WebAssembly + Blazor 的优缺点?
- ios - 在 Swift 中实现 MDC 滑块上的悬停状态
- design-patterns - 用于构建读/写包的设计模式
- postman - 邮递员,模式验证
- python - 为什么当我使用线程时我的 cv2.imshow() 停留在第一帧?