简体   繁体   中英

MongoDB update nested array elements

I have the following structure:

{
    id: "1",
    invoices: [{ id: "1", balance: 1},{ id: "2", balance: 1}]
},
{
    id: "2",
    invoices: [{ id: "3", balance: 1},{ id: "4", balance: 1}]
}

I'm getting a list of invoices IDs that i shouldn't update, the rest i need to update the balance to 0.

I'm pretty new to MongoDB and managing to find a way to do it.

First of all, you forgot the quotes around the field names. Your documents should be like this:

{
    "id": "1",
    "invoices": [{
        "id": "1",
        "balance": 1
    }, {
        "id": "2",
        "balance": 1
    }]
}

I have limited experience with MongoDB, as I learnt it this semester at University. However, here is my solution:

db.collection.update(
    { id: "1" },
    {
        $set: {
            "invoices.0": { id: "1", balance: 0 }
        }
     }
)

What does this solution do?

  1. It takes the document with id 1. That is your first document.
  2. The $set operator replaces the value of a field with the specified value. (straight out from the MongoDB manual - MongoDB Manual - $set operator ).
  3. "invoices.0" takes the first invoice from the invoices array and then it updates the balance to 100.
  4. Replace the word collection from db.collection with your collection name.

Try and see if it works. If not, I'd like someone with more experience to correct me.

LE: Now it works, try and see.

Let say you want to update all invoices of id 1 except invoice.id 2 try this one:

db.collection.update(
{ id: "1", "invoices.id": {$ne: 2} },
{
    $set: {
        "invoices.$[]": { balance: 0 }
    }
 }

)

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