user1055568
user1055568

Reputation: 1429

Update mongo array elements by index with c-driver

To update elements of a mongo array, I was using syntax like:

{"$set":{"a.0":1238},{"a.1":402}}

Or, more accurately, I was using the C-driver function calls that I think are equivalent to that. This seemed to work fine, but when I look at the object in MongoHub, I see:

a: {"0":1238,"1":402}

instead of:

a: [1238,402]

Does anyone know what is proper syntax to access array elements by index with C-driver? What I am doing now serves my immediate purpose, but I am not sure if there are significant performance differences. Also, I might later need to use operations that require true array.

Upvotes: 2

Views: 4268

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

If a field didn't exist, then this dot-notation query will create it as a hash (object) and assign values to keys of that hash. If field exists and is an array, it will behave as you expect. See this session.

> db.arrays.insert({});
> db.arrays.find();
{ "_id" : ObjectId("4f518c8b58713e4dbadbfb9f") }
> db.arrays.update({ "_id" : ObjectId("4f518c8b58713e4dbadbfb9f") }, {$set: {"a.0": 123}});
> db.arrays.find();
{ "_id" : ObjectId("4f518c8b58713e4dbadbfb9f"), "a" : { "0" : 123 } }


> db.arrays.insert({a: []})
> db.arrays.find();
{ "_id" : ObjectId("4f518c8b58713e4dbadbfb9f"), "a" : { "0" : 123 } }
{ "_id" : ObjectId("4f518cca58713e4dbadbfba0"), "a" : [ ] }
> db.arrays.update({ "_id" : ObjectId("4f518cca58713e4dbadbfba0") }, {$set: {"a.0": 123}});
> db.arrays.find();
{ "_id" : ObjectId("4f518c8b58713e4dbadbfb9f"), "a" : { "0" : 123 } }
{ "_id" : ObjectId("4f518cca58713e4dbadbfba0"), "a" : [ 123 ] }

Upvotes: 5

Related Questions