gpt4 book ai didi

ruby-on-rails - 如何使用 MongoDB 中的聚合框架执行此查询?

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:35 25 4
gpt4 key购买 nike

我正在尝试返回 minute 大于 12 的 visits

我的数据结构是这样的:

{ "_id" : "20120723/foobar/song/custom-cred",
"live_daily_count" : 4,
"metacontent" : { "date" : "20120723",
"live_daily_statable_slug" : "custom-cred",
"live_daily_statable_title" : "custom cred",
"live_daily_statable_type" : "Song",
"url" : "foobar/songs/custom-cred",
"user_slug" : "foobar" },
"visits" : [
{ "country_name" : "UK",
"iso_two_letter_country_code" : "UK",
"referer" : "http://localhost:3000/foobar/songs/no-title-with-space",
"minute" : 12,
"token_id" : "134300236111rcbmbmvv" },
{ "country_name" : "UK",
"iso_two_letter_country_code" : "UK",
"referer" : "http://localhost:3000/foobar/songs/no-title-with-space",
"minute" : 13,
"token_id" : "134300242111pjvkjjkf" },
{ "country_name" : "UK",
"iso_two_letter_country_code" : "UK",
"referer" : "http://localhost:3000/foobar/songs/no-title-with-space",
"minute" : 13,
"token_id" : "134300243511udbnqldm" }
]
}

我正在使用 Mongodb Ruby 驱动程序。我尝试了以下内容:

conn = Mongo::Connection.new
db = conn['foobar_development']
cmd = {
aggregate: 'live_daily_stats',
pipeline: [
{ '$match' => { :_id => "20120723/foobar/song/custom-cred" } },
{ '$project' => {
:visits => 1,
} },
{ '$unwind' => '$visits' },
# { '$group' => {
# :_id => '$_id'
# } },
]
}

res = db.command(cmd)['result']

现在返回:

[
[0] {
"_id" => "20120723/foobar/song/custom-cred",
"visits" => {
"country_name" => "UK",
"iso_two_letter_country_code" => "UK",
"referer" => "http://localhost:3000/foobar/songs/custom-cred",
"minute" => 12,
"token_id" => "134300236111rcbmbmvv"
}
},
[1] {
"_id" => "20120723/foobar/song/custom-cred",
"visits" => {
"country_name" => "UK",
"iso_two_letter_country_code" => "UK",
"follower_class" => "non_follower",
"referer" => "http://localhost:3000/foobar/songs/custom-cred",
"minute" => 13,
"token_id" => "134300242111pjvkjjkf"
}
},
[2] {
"_id" => "20120723/foobar/song/custom-cred",
"visits" => {
"country_name" => "UK",
"iso_two_letter_country_code" => "UK",
"follower_class" => "non_follower",
"referer" => "http://localhost:3000/foobar/songs/custom-cred",
"minute" => 13,
"token_id" => "134300243511udbnqldm"
}
}
]

如何确保结果只返回 minute 大于 12 的 visits?任何帮助将不胜感激。

最佳答案

您在开始时使用的 $match 管道元素可以多次使用,包括在您的 $unwind 步骤之后。

一旦 $unwind 将您的 visits 数组元素拆分到其自己的文档中,您可以将 {$match:{"visits.minute":{$gt:12}}} 添加到管道的末尾,这样应该只留下 visits你想要的。

关于ruby-on-rails - 如何使用 MongoDB 中的聚合框架执行此查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641358/

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