gpt4 book ai didi

MongoDB 通过 Id 数组删除嵌入的文档

转载 作者:行者123 更新时间:2023-12-04 11:38:55 32 4
gpt4 key购买 nike

我正在处理 Node.js使用 MongoDB 的应用程序数据库与 Mongoose .我一直被困在这件事上,没有提出正确的查询。
问题:
有一个名为 chats 的集合其中包含嵌入的文档 (rooms)作为对象数组。我想删除这些嵌入的文件 (rooms)通过 Ids哪些在数组中。

  {
"_id": "ObjectId(6138e2b55c175846ec1e38c5)",
"type": "bot",
"rooms": [
{
"_id": "ObjectId(6138e2b55c145846ec1e38c5)",
"genre": "action"
},
{
"_id": "ObjectId(6138e2b545c145846ec1e38c5)",
"genre": "adventure"
}
]
},
{
"_id": "ObjectId(6138e2b55c1765846ec1e38c5)",
"type": "person",
"rooms": [
{
"_id": "ObjectId(6138e2565c145846ec1e38c5)",
"genre": "food"
},
{
"_id": "ObjectId(6138e2b5645c145846ec1e38c5)",
"genre": "sport"
}
]
},
{
"_id": "ObjectId(6138e2b55c1765846ec1e38c5)",
"type": "duo",
"rooms": [
{
"_id": "ObjectId(6138e21c145846ec1e38c5)",
"genre": "travel"
},
{
"_id": "ObjectId(6138e35645c145846ec1e38c5)",
"genre": "news"
}
]
}
我正在转换我的数组 ids进入MongoDB ObjectId所以我可以使用这些 ID 作为匹配标准。
const idsRoom = [
'6138e21c145846ec1e38c5',
'6138e2565c145846ec1e38c5',
'6138e2b545c145846ec1e38c5',
];

const objectIdArray = idsRoom.map((s) => mongoose.Types.ObjectId(s));
并将此查询用于聊天集合。但它正在删除整个文档,我只想删除 rooms嵌入文档,因为 ids 数组仅用于嵌入文档。
Chat.deleteMany({ 'rooms._id': objectIdArray }, function (err) {
console.log('Delete successfully')
})
我真的很感谢你在这个问题上的帮助。

最佳答案

您必须使用 $pull update 中的运算符像这样查询:
此查询查找存在 _id 的文档进入 rooms数组和使用 $pull从数组中删除对象。

yourModel.updateMany({
"rooms._id": {
"$in": [
"6138e21c145846ec1e38c5",
"6138e2565c145846ec1e38c5",
"6138e2b545c145846ec1e38c5"
]
}
},
{
"$pull": {
"rooms": {
"_id": {
"$in": [
"6138e21c145846ec1e38c5",
"6138e2565c145846ec1e38c5",
"6138e2b545c145846ec1e38c5"
]
}
}
}
})
示例 here .
您也可以在没有 query 的情况下运行您的查询参数(在 update queries 中,第一个对象是 query ) like this结果是一样的。但是最好使用第一个对象指示 mongo 文档。

关于MongoDB 通过 Id 数组删除嵌入的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69124591/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com