0

If I have the following document in my database :

{
    "_id" : MainId,
    "subdoc" : [
        {
            "_id" : SubdocId,
            "userid" : "someid",
            "toupdate": false,
        },
        {
            "_id" : SubdocId2,
            "userid" : "someid2",
            "toupdate": false,
        }       
    ],
    "extra" : [
        "extraid1",
        "extraid2"
    ]
}

How can I update the subdocument SubdocId2 where the id (SubdocId2) must match and either SubdocId2's userid is "someid2" OR value "extraid1" exists in "extra"?

The farthest I got is:

db.coll.update({
"subdoc._id":"SubdocId2", {
    $or: ["extra":{$in:["extraid1"]}, "subdoc.userid":"someid2"]
    }
}, {"subdoc.$.toupdate":true})

Maybe I forgot to quote up something, but I get an error (SyntaxError: invalid property id)

3
  • SubdocId2 is a string? Commented Jan 17, 2020 at 23:59
  • Technically it's an ObjectId. Commented Jan 18, 2020 at 0:01
  • ok, so in your update you need to use an ObjectId. "subdoc._id": ObjectId('SubdocId2'). You're using a string Commented Jan 18, 2020 at 1:56

1 Answer 1

1

Please try this :

db.coll.update(
    {
        $and: [{ "subdoc._id": SubdocId2 }, {
            $or: [{ "extra": { $in: ["extraid1"] } },
            { "subdoc.userid": "someid2" }]
        }] // subdoc._id && (extra || subdoc.userid)
    }, { $set: { "subdoc.$.toupdate": true } })

In your query there are couple of syntax issues & also if you don't use $set in your update part - it replace the entire document with "subdoc.$.toupdate": true. Of course if you're using mongoose that's different scenario as mongoose will internally does add $set but when executing in shell or any client you need to specify $set. Also if SubdocId2 is ObjectId() you need to convert string to ObjectId() in code before querying database.

Sign up to request clarification or add additional context in comments.

1 Comment

Works great! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.