0

I'm iterating on a query results computing an array of float values. Now from C++ I want to add it to the originating record, or, if already present, update it.

From Javascript I do something similar to:

db.scraps.find({type: {$exists: 0}}).forEach(function (doc) {
    var new_array = []
    // fill the elements of new_array from doc fields

    doc.new_field = new_array;
    db.scraps.save(doc);
}

Seems that this cannot be done with the C++ driver (I'm still running 2.6) except using update. If true, I think I should have to save in an array the pair (OID, new_array) from my query and then iterating on it calling: conn.update("kb.scraps", QUERY("_id" << OID), BSON("new_field" << new_array))

Thanks for your help!

SiliconValley
  • 1,465
  • 17
  • 30
  • The `.save()` and .`.update()` methods are really not all that different. In the API's that implement `.save()` it is generally basically a wrapper around `.update()` with an "upsert" option, and some of it's own object property handling. So in general cases if you are adding an array property to an existing document then you employ a [`$set`](https://docs.mongodb.org/v3.0/reference/operator/update/set/) operation. So it's a bit unclear in your question, but it seems like you are possibly asking how to `$set` the array property without overwriting the rest of the document. So you use `$set`. – Blakes Seven Nov 14 '15 at 09:41
  • You are right, I really ask two questions: 1) Could I update a document for which I have a cursor on it (ie a document in a list of query results); 2) How to do this. And thanks, now I investigate $set from C++. – SiliconValley Nov 14 '15 at 11:21
  • I suspected that you have little understanding of MongoDB or general database principles. You can **never** update on a "cursor" in any respectible architecture. The only thing you ever really get is a "reference" to the document for which your next "update" needs to be constructed ( been a long time since I worked with dBase, and this is not a plain linked list, but a database ). You did basically seem to be misundertanding the concept of `.update()` as a method. Therefore please look at `$set` and spend some time on general API as well, since you don't seem very familiar with it. – Blakes Seven Nov 14 '15 at 11:26
  • Solved: in the query I fill an array of oids and an array of the computed arrays, then looping on them: ```conn.update(Namespace, QUERY("_id" << oids[i]), BSON("$set" << BSON("new_field" << array_of_new_array[i])));``` In the original question was mislead by js apparently doing all in the same query loop (and I had a brief brain disconnection too...). Thanks! – SiliconValley Nov 14 '15 at 13:58

0 Answers0