Updating multiple complex array elements in MongoDB -
I know that has been asked before, but I have not found a solution that works efficiently so far. I am working with the MongoDB C # driver, though it is more of a general question about MongoDB operation.
I have a document structure that looks like this:
field 1: value1 field 2: value2 ... user: [... .. User 1 sub-document ...}, {... user2 sub-document ...}, ...
Some facts:
- < Li> Each user subdown contains further sub-array & amp; Sub-documents (hence they are quite complex)
- The average user array consists of only 5 elements, but the worst case may exceed 100.
- In this system, several thousand update operations can be done to many users per day. At one time, the large arrays on one document will receive more frequent updates due to their data size.
I am trying to explain how to do it efficiently. From everything I've heard, you can not set many array elements directly to new values together, so I had to try something else.
I tried to remove the old array using $ pullAll / $ AddToSet + $ each operation and replaced it with one modified one. I know that the $ pullall can only remove those elements I also need, but I would like to preserve the order of elements
users ", new users .ORA () ));} Hold (WriteConcernException wce) {return wce.Message;}
In this case, the new user will have a list & lt; BsonValue & gt;
The array is converted though I am getting the following exception message:
'User' and 'User' at the same time
By showing this, I can not have two update statements in the same writing operation on the same field.
I also have the Setting ("user", new user .ORA ())
, but apparently does not work with set statement arrays, only the original value:
< P> Logic 2: From 'MongoDB.Bson.BsonValue []' 'can not be converted to' MongoDB.Bson.BsonValue '
Then I passed that array Try Rthyt a BsonDocument:
updates. Set ( "user", the new user Koaarara (). ToBsonDocument ());
and found this:
An array value can not be written at the basic level of a BSON document.
I can try to change the whole document, but it seems that redundancy is definitely not very efficient
So the only thing that I think It is to run two different writing tasks: To remove an unwanted old users and to replace the other with their new versions:
Connection Result wcr = collection .Update (Query, Update.Paul All ("Users")); WriteConcernResult wcr = collection.Update (query, update addToSetEach ("users", newUsers.ToArray ()));
Is this my best choice? Or is there a better way to do this?
Your code should work with a minor change:
Update: Set ("Users", New BsonArray (newUsers));
BsonArray is a BsonValue, where there is no array of documents and we do not convert the array to the other basic values.
Comments
Post a Comment