【问题标题】:Query on the last element of an array in MongoDB when the array size is stored in a variable当数组大小存储在变量中时,查询 MongoDB 中数组的最后一个元素
【发布时间】:2016-12-25 13:39:46
【问题描述】:

我在 MongoDB 中有一个数据集,这是我的一行数据的示例:

{ "conversionDate": "2016-08-01",
  "timeLagInDaysHistogram": 0,
  "pathLengthInInteractionsHistogram": 4,
  "campaignPath": [ 
      {"campaignName": "name1", "source": "sr1", "medium": "md1", "click": "0"},
      {"campaignName": "name2", "source": "sr1", "medium": "md1", "click": "0"},
      {"campaignName": "name1", "source": "sr2", "medium": "md2", "click": "1"},
      {"campaignName": "name3", "source": "sr1", "medium": "md3", "click": "1"} 
  ],
  "totalTransactions": 1,
  "totalValue": 37.0,
  "avgCartValue": 37.0
}

(campaignPath的长度不是固定的,所以每一行可以有不同数量的元素。

我想在campaignPath的最后一个元素中找到匹配“source = sr1”的元素。

我知道我不能用类似的东西进行查询

db.paths.find(
    {
        'campaignPath.-1.source': "sr1"
    }
)

但是,由于我存储的“pathLengthInInteractionsHistogram”等于campaignPath 长度的长度,我不能这样做:

db.paths.find(
    {
        'campaignPath.$pathLengthInInteractionsHistogram.source': "sr1"
    }
)

【问题讨论】:

  • @JohnnyHK 我想要整个文档,因为我需要日期和其他信息。

标签: mongodb bigdata database


【解决方案1】:

从 MongoDB 3.2 开始,您可以使用 aggregate 执行此操作,它提供了 $arrayElemAt 运算符,该运算符接受 -1 索引来访问最后一个元素。

db.paths.aggregate([
  // Project the original doc along with the last campaignPath element
  {$project: {
    doc: '$$ROOT',
    lastCampaign: {$arrayElemAt: ['$campaignPath', -1]}
  }},
  // Filter on the last campaign's source
  {$match: {'lastCampaign.source': 'sr1'}},
  // Remove the added lastCampaign field
  {$project: {doc: 1}}
])

在早期版本中,您无法使用$where。这会起作用,但性能很差:

db.paths.find({
    $where: 'this.campaignPath[this.pathLengthInInteractionsHistogram-1].source === "sr1"'
})

你也可以不用pathLengthInInteractionsHistogram

db.paths.find({$where: 'this.campaignPath[this.campaignPath.length-1].source === "sr1"'})

【讨论】:

  • 谢谢!当我们升级我们的数据库版本(我们在 3.0 中运行)时,我会尝试这个。只是“为了科学”。这可以在 3.0 中完成吗?
猜你喜欢
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 2022-08-03
  • 2014-10-10
  • 2020-04-12
相关资源
最近更新 更多