如何在此文档结构中更新数组中的项目?

时间:2012-07-25 22:04:04

标签: ruby-on-rails ruby ruby-on-rails-3 mongodb

我有以下文档结构:

{
  "_id" : "20120725/foobar/song/test-pg3-long-title-here-test-lorem-ipsum-dolor-lo",
  "live_daily_count" : 4,
  "metacontent" : { "date" : "20120725",
    "live_daily_statable_slug" : "test-pg3-long-title-here-test-lorem-ipsum-dolor-lo",
    "live_daily_statable_title" : "test pg3 long title here test lorem ipsum dolor lorem ipsume dolor long description here msam dfam sdfm asfa sfasfas df as f as fas f sa f",
    "live_daily_statable_type" : "Song",
    "url" : "foobar/songs/test-pg3-long-title-here-test-lorem-ipsum-dolor-lo",
    "user_slug" : "foobar" },
  "visits" : [
    { "country_name" : "UK",
      "iso_two_letter_country_code" : "UK",
      "referer" : "http://localhost:3000/",
      "minute" : 1121,
      "token_id" : "13432416893tlfsmmgh" },
    { "country_name" : "UK",
      "iso_two_letter_country_code" : "UK",
      "referer" : "http://localhost:3000/",
      "minute" : 1281,
      "token_id" : "13432512733xcqhhrqs" },
    { "country_name" : "UK",
      "iso_two_letter_country_code" : "UK",
      "referer" : "http://localhost:3000/",
      "minute" : 1285,
      "token_id" : "13432515303rwiaczcx" },
    { "country_name" : "UK",
      "iso_two_letter_country_code" : "UK",
      "referer" : "http://localhost:3000/",
      "minute" : 1288,
      "token_id" : "13432517303eusgjcgz" }
  ]
}

如何通过token_id 13432515303rwiaczcx找到访问权限并将其minute更新为1234?

我可以使用聚合框架(下面的代码)find数组中的项目,但是如何更新呢?

  connection = Mongo::Connection.new
  database   = conn['foobar_development']

  query = {
    aggregate: 'live_daily_stats',
    pipeline: [
      { '$project' => {
        :visits => 1,
      } },
      { '$unwind' => '$visits' },
      { '$match' => { 'visits.token_id' => '13432515303rwiaczcx' } },
    ]
  }

  visit = database.command(query)['result'][0]

返回:

{
       "_id" => "20120725/foobar/song/test-pg3-long-title-here-test-lorem-ipsum-dolor-lo",
    "visits" => {
                                      "country_name" => "UK",
                       "iso_two_letter_country_code" => "UK",
                                           "referer" => "http://localhost:3000/",
                                            "minute" => 1285,
                                          "token_id" => "13432515303rwiaczcx"
    }
}

1 个答案:

答案 0 :(得分:1)

聚合框架不是为了更新集合中的现有文档而设计的。正如idefine指出的那样,你可以使用位置运算符:

输入:

{
  "_id" : xyz
  "visits" : [
    {"minute" : 1281,
      "token_id" : 1 },
    { "minute" : 1285,
      "token_id" : 2 },
    { "minute" : 1288,
      "token_id" : 3 }
  ]
}

更新

db.collection.update({"visits.token_id":2}, {$inc:{"visits.$.minute":1}})

结果:

{
  "_id" : xyz
  "visits" : [
    {"minute" : 1281,
      "token_id" : 1 },
    { "minute" : 1286,
      "token_id" : 2 },
    { "minute" : 1288,
      "token_id" : 3 }
  ]
}