2

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.

2
  • Might be wrong but have you tried syntax like {"$set":{"a": {1238, 402}}} Commented Mar 3, 2012 at 3:14
  • 1
    @Hank: that's invalid syntax. Commented Mar 3, 2012 at 3:19

1 Answer 1

5

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 ] }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works. As long as I use explicit array syntax to initialize the field, then subsequent updates work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.