gpt4 book ai didi

ruby - 在单个嵌入式文档中更新 MongoDB 中的单个字段

转载 作者:可可西里 更新时间:2023-11-01 09:12:35 25 4
gpt4 key购买 nike

我们有一些嵌入式文档,如下所示:

 {
"_id" : ObjectId("4e402353bc9f6ec5a6000001"),
"first_name" : "Chris",
"last_name" : "Jones",

"alerts" : [
{
"_id" : ObjectId("4f7cd6ffc067db00070022d4"),
"name" : "Default",
"email_frequency" : "weekly",
"interested_industries" : [
"Computer Software",
"Internet"
],
"interested_employers" : [
"Facebook",
"AOL"
],
"interested_skills" : [ ],
"matches" : [
ObjectId("4ee46a2a0dd0c70017000365"),
ObjectId("4efa1707bacfa40001012b65"),
ObjectId("4e402376bc9f6ec5a6000a7a"),
ObjectId("4e4e0eb8d052fc4028021f66"),
ObjectId("4ee55d8500ca410014000003"),
ObjectId("4ee63d06d96b850001008688"),
ObjectId("4e57be7ed052fc606a002335"),
ObjectId("4f05d47d9ce340001702ba42"),
ObjectId("4f200ffcaf5f34000e0021a4"),
ObjectId("4e4de701d052fc33da00052f")
],
"updated_at" : ISODate("2012-05-03T18:26:14.774Z")
}
]
}

由于上面的文档包含在一个数组中,所以我无法通过这样的选择器将其挑选出来:

User.collection.update({"_id" => user.id}, {:$set => {"alert.matches" => matches}})

但这将更新所有#alerts 匹配项。我只想更新 ID 为“4fa7fd60e5be08bcc9000644”的警报。

最佳答案

您或许可以使用 positional operator识别数组元素:

The $ positional operator

The $ operator (by itself) means "position of the matched array item in the query". Use this to find an array member and then manipulate it.

所以也许是这样的:

User.collection.update(
{ :_id => user.id, :matches => BSON::ObjectId('4e40238dbc9f6ec5a6000eed') },
{ :$set => { 'alert.matches.$' => matches } }
)

但正如 Sergio 指出的那样,很难根据您问题中的有限信息梳理出您的文档结构。


看起来在我回答后收到了更多信息,它看起来像:

{ :$set => { 'alerts.$.matches' => ... } }

是你需要的。并且您需要在查询中包含 :matches 以便 $ 有一些东西可以引用。

关于ruby - 在单个嵌入式文档中更新 MongoDB 中的单个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10506316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com