是否可以汇总通过DBRef存储的数据?
Is it possible to aggregate on data that is stored via DBRef?
Mongo 2.6
Mongo 2.6
假设我有交易数据,例如:
Let's say I have transaction data like:
{ _id : ObjectId(...), user : DBRef("user", ObjectId(...)), product : DBRef("product", ObjectId(...)), source : DBRef("website", ObjectId(...)), quantity : 3, price : 40.95, total_price : 122.85, sold_at : ISODate("2015-07-08T09:09:40.262-0700") }诀窍是源"本质上是多态的-可能是不同的$ ref值,例如网页","call_center"等也具有不同的ObjectId.例如,DBRef("webpage",ObjectId("1"))和DBRef("webpage",ObjectId("2"))将是两个不同的发起交易的网页.
The trick is "source" is polymorphic in nature - it could be different $ref values such as "webpage", "call_center", etc that also have different ObjectIds. For example DBRef("webpage", ObjectId("1")) and DBRef("webpage",ObjectId("2")) would be two different webpages where a transaction originated.
我最终希望在一段时间(例如一个月)内按来源进行汇总:
I would like to ultimately aggregate by source over a period of time (like a month):
db.coll.aggregate( { $match : { sold_at : { $gte : start, $lt : end } } }, { $project : { source : 1, total_price : 1 } }, { $group : { _id : { "source.$ref" : "$source.$ref" }, count : { $sum : $total_price } } } );诀窍是,尝试通过按$分组或尝试通过项目使用表达式进行转换时,尝试使用以$开头的变量时遇到路径错误.
The trick is you get a path error trying to use a variable starting with $ either by trying to group by it or by trying to transform using expressions via project.
有什么办法吗?实际上,尝试通过聚合将这些数据推送到一个子集合以在该子集合上进行操作.尝试避免对数百万条记录进行大的游标操作以转换数据,以便我可以对其进行汇总.
Any way to do this? Actually trying to push this data via aggregation to a subcollection to operate on it there. Trying to avoid a large cursor operation over millions of records to transform the data so I can aggregate it.
推荐答案Mongo 4.通过以下方式解决了此问题: 具有以下结构:
Mongo 4. Solved this issue in the following way: Having this structure:
{ "_id" : LUUID("144e690f-9613-897c-9eab-913933bed9a7"), "owner" : { "$ref" : "person", "$id" : NumberLong(10) }, ... ... }我需要使用"owner.$ id"字段.但是由于字段名中的"$",我无法使用聚合. 我使用以下代码段转换了"owner.$ id"->"owner":
I needed to use "owner.$id" field. But because of "$" in the name of field, I was unable to use aggregation. I transformed "owner.$id" -> "owner" using following snippet:
db.activities.find({}).aggregate([ { $addFields: { "owner": { $arrayElemAt: [{ $objectToArray: "$owner" }, 1] } } }, { $addFields: { "owner": "$owner.v" } }, {"$group" : {_id:"$owner", count:{$sum:1}}}, {$sort:{"count":-1}} ])此处的详细说明- dev.to/saurabh73/mongodb-using-aggregation-pipeline-to-extract-dbref-using-lookup-operator-4ekl
更多推荐
使用DBRef进行MongoDB聚合
发布评论