【问题标题】:How to update an array of subdocuments with R mongolite?如何使用 R mongolite 更新子文档数组?
【发布时间】:2017-07-20 18:14:57
【问题描述】:

我正在使用 R mongolite 在具有以下结构的 mongo 集合中进行读写:

[{_id: 1, name: a, sites: [
  {ref: site_a1},
  {ref: site_a2}
]},
{_id: 2, name: b, sites: [
  {ref: site_b1},
  {ref: site_b2}
]},
{_id: 3, name: c, sites: [
  {ref: site_c1},
  {ref: site_c2},
  {ref: site_c3},
  {ref: site_c4}
]}]

对于我收藏的给定文档,我想为每个站点添加一些属性。例如,我想像这样更新第一个文档:

{_id: 1, name: a, sites: [
  {ref: site_a1, lat: 10, lng: 20},
  {ref: site_a2, lat: 5, lng: 40}
]}

在 mongolite 中,我可以将站点作为数据框获取并计算所需的属性:

sites <- db$find(query = '{"name": 1}',
        fields='{"_id": 0, "name": 0}')$sites[[1]]
loc <- getLatLng(sites)
# loc is a dataframe with lat and lng for each site

但我找不到更新数据库的方法。我试过了:

db$update(query = '{"name": 1}',
           update = paste0('{"$push":{"sites": {"$each":',jsonlite::toJSON(loc),'}}}'),
           upsert = FALSE, multiple = FALSE)

不出所料地给了我:

{_id: 1, name: a, sites: [
  {ref: site_a1},
  {ref: site_a2},
  {lat: 10, lng: 20},
  {lat: 5, lng: 40}
]}

有没有办法通过将新属性添加到数组的现有元素来更新站点字段,或者我应该用$set 替换整个站点字段?感谢您的帮助。

我猜我的问题与this question 有关,所以我可能需要遍历数组的每个元素...

【问题讨论】:

    标签: r mongodb mongolite


    【解决方案1】:

    以下似乎可以解决问题:

    sites <- db$find(query = '{"name": 1}',
            fields='{"_id": 0, "name": 0}')$sites[[1]]
    loc <- getLatLng(sites)
    
    for (i in 1:nrow(sites)){
      db$update(query = paste0('{"name": 1, "sites.ref":', sites$ref[i],'}'),
                update = paste0('{"$set":{"sites.$.lat":',loc[i, "lat"],'},
                                 "$set":{"sites.$.lon":',loc[i, "lng"],'}}'))
    }
    

    如果有更好的方法,仍然感兴趣......

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 2023-03-31
      • 2016-11-23
      • 2020-06-07
      • 2017-03-31
      • 2016-01-09
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多