[英]Update nested hash MongoDB - Ruby
I'm trying to update a hash in a MongoDB doc with a simple value but it store the value in an array. 我试图用一个简单的值更新MongoDB文档中的哈希,但是它将值存储在数组中。 I use the ruby driver for mongo 我为mongo使用ruby驱动程序
Code will explain better because my english is bad. 代码会更好地解释,因为我的英语不好。
What I have : 我有的 :
{
'id' : ...
'stream' : {
"1406481985(a timestamp)" : 35603
}
}
What I want : 我想要的是 :
{
'id' : ...
'stream' : {
"1406481985" : 35603,
"1406481990" : 15000
}
}
What I get : 我得到的是:
{
'id' : ...
'stream' : {
"1406481985" : 35603,
"1406481990" : [
15000
]
}
}
How did I get there : 我如何到达那里:
views = 15000
time = Time.now
coll.find_and_modify({
query: {:id => id},
update: {'$push' => {"stream.#{time}" => views}},
})
I've already tried with Updating nested document in MongoDB and I can't see what I do wrong 我已经尝试过在MongoDB中更新嵌套文档,但看不到我做错了什么
Daniël Knippers is correct — using $set
should work. DaniëlKnippers是正确的-使用$set
应该可以。 I also notice you are using id
instead of '_id`. 我还注意到您正在使用id
而不是'_id`。 Perhaps a typo? 也许是错字?
edit: note that it's usually not recommended to have dynamic key values as they are difficult to index and query. 编辑:请注意,通常不建议使用动态键值,因为它们很难索引和查询。 Consider a stream
structure of hashes inside an array: 考虑数组内部的哈希stream
结构:
{
'_id' : ...
'stream' : [
{'time' : 1406481985, 'views': 35603},
{'time' : 1406481990, 'views': 15000}
]
}
Now you can easily query the time
and views
fields. 现在,您可以轻松查询time
和views
字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.