0

我有以下文档结构:

{
  "_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"
    }
}
4

1 回答 1

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 }
  ]
}
于 2012-07-25T22:46:37.853 回答