S
S
Stanislav2016-04-29 02:11:07
MongoDB
Stanislav, 2016-04-29 02:11:07

How to update values ​​in an array of objects?

It is required to update the values ​​of some elements in the array with an object
For example, there is a document

{
    "url": "link",
    "comments": [{
        "user": "user1",
        "field": 1
    },{
        "user": "user1",
        "field": 1
    },{
        "user": "user2",
        "field": 1
    },{
        "user": "user3",
        "field": 1
    }]
}

It is necessary for comments.user === user1 to change the value of comments.field
Now, in order to do this, I am engaged in "perversion", I get all the comments, then in a cycle, subject to the condition, I update the necessary element of the object. Those. with 1000 comments, you need to check 1000 times, and it is possible to execute the update request 100 times of them.
Is it possible to do this in a simpler way now?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2016-04-29
@lega

In fact, the field field is a checkbox for sending notifications, i.e. 0 do not send a response to the user, 1 send.

If you need to enable / disable the value for all comments within the user, then why store this value in each comment.
To update by key, use a dictionary instead of an array.
Example:
{
  comments: [],
  flags: {
    user1: true,
    user2: false
  }
}
With this structure, you can enable/disable the flag by user for all comments (the entire document), and if you need the ability to switch specific comments, you can store user-comment side by side ( flagsByComments:{ user2: {comment1: true, comment2: false} }).
About the complexity of the update, if you have 1 record per 1000 reads, then it’s not scary that the update is difficult, the main thing is that the readings are fast.
With a lock, one update will be enough (well, +1 update for a lock, although not necessarily, it depends on the type of lock)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question