如何通过数组键删除mongoose中的子文档?

时间:2021-05-23 02:37:10

I have a document like this:

我有一个这样的文件:

{
  project: 'Book',
  author: 'Author',
  pages: [{},{},{},{}]
}

for example I want to remove second element from pages array. I try to do something like this:

例如,我想从pages数组中删除第二个元素。我尝试做这样的事情:

db.t.update(_id: "53296f43630a817c1af2a3e8"}, {$pull:{'test.$':1}})

but it isn't work for me.

但它对我不起作用。

1 个解决方案

#1


1  

Well the way you put it, it's going to be hard to match because there is nothing in there. But in the real world you would probably try to match like this:

那么你说它的方式,它很难匹配,因为那里什么也没有。但在现实世界中你可能会尝试像这样匹配:

db.t.update(
    { "_id": "53296f43630a817c1af2a3e8" }, 
    { "$pull": { "pages": { "value": 1 } }
)

That is assuming that there is a "value" property in the "sub-document".

这是假设“子文档”中存在“值”属性。

But if you really do mean something like this where the is nothing to match, then try this:

但是,如果你确实意味着这样的东西无法匹配,那么试试这个:

db.t.update(
    { "_id": "53296f43630a817c1af2a3e8" }, 
    { "$set": { "pages.1": false } }
);

db.t.update(
    { "_id": "53296f43630a817c1af2a3e8" }, 
    { "$pull": { "pages": false } }
)

Which sets a value you can match and then matches and removes it.

哪个设置了您可以匹配的值,然后匹配并删除它。

#1


1  

Well the way you put it, it's going to be hard to match because there is nothing in there. But in the real world you would probably try to match like this:

那么你说它的方式,它很难匹配,因为那里什么也没有。但在现实世界中你可能会尝试像这样匹配:

db.t.update(
    { "_id": "53296f43630a817c1af2a3e8" }, 
    { "$pull": { "pages": { "value": 1 } }
)

That is assuming that there is a "value" property in the "sub-document".

这是假设“子文档”中存在“值”属性。

But if you really do mean something like this where the is nothing to match, then try this:

但是,如果你确实意味着这样的东西无法匹配,那么试试这个:

db.t.update(
    { "_id": "53296f43630a817c1af2a3e8" }, 
    { "$set": { "pages.1": false } }
);

db.t.update(
    { "_id": "53296f43630a817c1af2a3e8" }, 
    { "$pull": { "pages": false } }
)

Which sets a value you can match and then matches and removes it.

哪个设置了您可以匹配的值,然后匹配并删除它。