node.js - 使用 MongoDB 从以下代码中的文档中的数组中删除对象?
问题描述
- 下面给出的是我的文档,我需要从文档中删除一个对象的评论数组,这样我就可以从前端传递文档 ID,使用 postId。
- 我是结构请帮助我。
{
likes: [],
_id: 5ea4375f49e4355094073330,
title: 'abc',
body: 'abc',
photo: 'no pic',
postedBy: 5e9aa457de91831e5c9f5005,
comments: [
{
_id: 5ea437c2a584ce5ac0147da1,
text: 'sadsadsad',
postedBy: [Object]
},
{
_id: 5ea437c5a584ce5ac0147da2,
text: 'sadsadsad',
postedBy: [Object]
},
{
_id: 5ea437c7a584ce5ac0147da3,
text: 'sadsadsad',
postedBy: [Object]
}
],
__v: 0
}
解决方案
如果要从数组中删除特定元素,comments
可以使用以下查询:
db.mycollection. updateOne(
{'_id': ObjectId("5ea4375f49e4355094073330")},
{ $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);
如果要从集合中的每个元素中删除注释对象,只需从update
. 像这样的东西:
db.mycollection.updateMany(
{ },
{ $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);
推荐阅读
- oracle - Oracle Reports (6i): Get difference of two items from two different queries (Multi Query Report)
- javascript - custom modal does not appear react.js
- c++ - How to automaticly deduce template parameter for a function parameter of type `basic_string_view` or the like?
- excel - Using offset formula with CountIf for column
- html - div 定位(y 轴)与之前的 div y 轴位置相同,不需要的行为
- sql - 比较表 column_name 与视图 column_names
- python - Python to slack text Integration
- excel - 用于生成二维码的 VBA 代码,但代码从哪里开始?
- c++ - 类型别名的推导指南 ->
- webpack - 使用 wepack 在 sass 中添加“假”网址