使用c-driver通过索引更新mongo数组元素 [英] Update mongo array elements by index with c-driver
问题描述
要更新mongo数组的元素,我使用的语法如下:
To update elements of a mongo array, I was using syntax like:
{"$set":{"a.0":1238},{"a.1":402}}
或者,更准确地说,我正在使用我认为与之等效的C驱动程序函数调用.这似乎工作正常,但是当我在MongoHub中查看该对象时,我看到:
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}
代替:
a: [1238,402]
有人知道使用C驱动程序通过索引访问数组元素的正确语法是什么吗?我现在正在做的事情符合我的近期目标,但是我不确定性能是否存在重大差异.另外,以后可能需要使用需要真实数组的操作.
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.
推荐答案
如果字段不存在,则此点符号查询会将其创建为哈希(对象),并将值分配给该哈希的键.如果field存在并且是一个数组,它将表现出预期的效果.观看本次会议.
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 ] }
这篇关于使用c-driver通过索引更新mongo数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!