当数组大小存储在变量中时,查询MongoDB中数组的最后一个元素

时间:2016-08-18 14:51:19

标签: mongodb bigdata database

我在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的长度不是常数,因此每行可以有不同数量的元素。

我想找到符合" source = sr1"的元素。 在campaignPath的最后一个元素

我知道我不能用

这样的查询
db.paths.find(
    {
        'campaignPath.-1.source': "sr1"
    }
)

但是,因为我有" pathLengthInInteractionsHistogram"存储的等于广告系列路径长度的长度,我不会做类似的事情:

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

1 个答案:

答案 0 :(得分:0)

从MongoDB 3.2开始,您可以使用aggregate执行此操作,-1提供$arrayElemAt运算符,该运算符接受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"'}) 的情况下执行此操作:

let e = StaticEnum() // error: 'StaticEnum' cannot be constructed because it has no accessible initializers
let s = StaticStruct() // Useless, but legal