Retrieve item list by checking multiple attribute values in MongoDB in golang

坚强是说给别人听的谎言 提交于 2019-12-01 17:51:46

You'd need to use the aggregation framework where you would run an aggregation pipeline that first filters the documents in the collection based on the venueList ids using the $match operator.

The second pipeline would entail flattening the venueList and sum subdocument arrays in order for the data in the documents to be processed further down the pipeline as denormalised entries. The $unwind operator is useful here.

A further filter using $match is necessary after unwinding so that only the documents you want to aggregate are allowed into the next pipeline.

The main pipeline would be the $group operator stage which aggregates the filtered documents to create the desired sums using the accumulator operator $sum. For the desired result, you would need to use a tenary operator like $cond to create the independent count fields since that will feed the number of documents to the $sum expression depending on the name value.

Putting this altogether, consider running the following pipeline:

db.collection.aggregate([
    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },
    { "$unwind": "$venueList" },
    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },
    { "$unwind": "$venueList.sum" },    
    {
        "$group": {
            "_id": null,
            "linux": {
                "$sum": {
                    "$cond": [ 
                        { "$eq": [ "$venueList.sum.name", "linux" ] }, 
                        "$venueList.sum.value", 0 
                    ]
                }
            },
            "ubuntu": {
                "$sum": {
                    "$cond": [ 
                        { "$eq": [ "$venueList.sum.name", "ubuntu" ] }, 
                        "$venueList.sum.value", 0 
                    ]
                }
            }
        }
    }
])

For usage with mGo, you can convert the above pipeline using the guidance in http://godoc.org/labix.org/v2/mgo#Collection.Pipe


For a more flexible and better performant alternative which executes much faster than the above, and also takes into consideration unknown values for the sum list, run the alternative pipeline as follows

db.collection.aggregate([
    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },
    { "$unwind": "$venueList" },
    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },
    { "$unwind": "$venueList.sum" },    
    { 
        "$group": {
            "_id": "$venueList.sum.name",
            "count": { "$sum": "$venueList.sum.value" }
        }
    },
    { 
        "$group": {
            "_id": null,
            "counts": {
                "$push": {
                    "name": "$_id",
                    "count": "$count"
                }
            }
        }
    }
])
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!