简体   繁体   中英

How to remove subdocument in mongoose by array key?

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:

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

but it isn't work for me.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM