Need help with query for subobject

Hello, I am a new to MongoDB and I seeking help.

I have a document in my collection that looks like this:

_id:5f2f40b8d1287d5c98309cb9
foo: "Some value"
zed: "Another Thing"
items: Object
    item_16414803554: Object
        name: "Some Name"
        age: "45"
    item_16414806548: Object
        name: "Some Name"
        age: "45"

I am using mongojs to work with the data and I need to remove one of the sub objects like “item_16414806548”. I cannot figure out what the query should be to do so.

I tried this:

db.mycollection.remove({_id: mongojs.ObjectId(id)}, {items: {_id: {$eq: itemid }}}, function(err, doc) {
res.json(doc);
});

But that’s not working. Can anyone tell me what the proper query would be? Thanks for any help!

Hi, .remove() will actually remov the whole document, not part of document. What you might want to do is to update a document to set/unset a key in it.
Try - .updateOne({//matching conditions}, {$unset:{"items.item_16414806548": ""}})
This will unset (update the document to remove that key) the key, and when you write it in dot notation, it can access the internal key item_16414806548 from items.
Checkout - $unset

1 Like

Thank you! Going to give that a try! Is there a way I can pass the items.item_16414806548 in as a variable. I cannot seem to put a variable in there to save my life. Thanks again for responding!

1 Like

Try -

key_var = "items.item_16414806548"
db.coll.updateOne({/*matching conditions*/}, {$unset:{ key_var : ""}})
1 Like

Ok, I will! Thanks again!

Just wanted to let you know that your advice was greatly appreciated! Because of you I got it to work. Thank you so much!!

2 Likes