有没有一种方法可以向mongodb查询添加计数器?

时间:2019-09-17 21:18:50

标签: mongodb

我想在与查询匹配的文档中添加一个计数器。例如,第一个文档的计数器= 1,第二个文档的计数器= 2,依此类推。

以下是数据片段:

"_id": ObjectId("5d1b9aea5c1dd54e8c773f42")
"timestamp":
    [ 
      "systemTimestamp":    2019-07-02T17:56:53.765+00:00
      "serverTimestamp":    0001-01-01T00:00:00.000+00:00
      "systemTimeZone":     "System.CurrentSystemTimeZone"
    ]
"urlData":
    [0]:
        "fullUrl":"https://imgur.com/gallery/EfaQnPY"

"UID":"00000-W3W6C42GWTRE960"
"safety": "safe"

我的查询(这是从Compass UI复制的):

$match: 
{
    $and: [{"UID": "00000-WVUCW3JW7OTHDVE"},
       {"timestamp.serverTimestamp": 
              {
               $gte:ISODate("2019-08-01T00:00"), 
               $lte:ISODate("2019-09-30T00:00")
               }}]
}

$unwind:
{
    path: "$urlData",
    includeArrayIndex: 'index'
}

$match:
{
    "index": 0
}

$project:
{
    _id: 0,
    date: { $dateToString: {
    format: "%Y-%m-%d",
    date: "$timestamp.serverTimestamp"}},
    safety: "$safety",
    url: "$urlData.fullUrl",
    UID: "$UID"
}

是否可以在$ project中添加一些内容以包含计数器?

1 个答案:

答案 0 :(得分:0)

问题本身就有答案。如果将最后一个管道的输出添加到数组中并再次使用所包含的索引进行展开,则可以得到预期的输出。

比方说,我有以下数据:

{
    "_id" : ObjectId("5d81c3b7a832f81a9e02337b"),
    "first" : "John",
    "last" : "Smith"
}
{
    "_id" : ObjectId("5d81c3b7a832f81a9e02337c"),
    "first" : "Alice",
    "last" : "Johnson"
}
{
    "_id" : ObjectId("5d81c3b7a832f81a9e02337d"),
    "first" : "Bob",
    "last" : "Williams"
}

在运行以下查询时:

db.collection.aggregate([
    {
        $group:{
            "_id":null,
            "data":{
                $push:"$$ROOT"
            }
        }
    },
    {
        $unwind:{
            "path":"$data",
            includeArrayIndex: 'counter'
        }
    },
    {
        $addFields:{
            "data.counter":{
                $sum:["$counter",1]
            }
        }
    },
    {
        $replaceRoot:{
            "newRoot":"$data"
        }
    }
]).pretty()

输出为:

{
    "_id" : ObjectId("5d81c3b7a832f81a9e02337b"),
    "first" : "John",
    "last" : "Smith",
    "counter" : 1
}
{
    "_id" : ObjectId("5d81c3b7a832f81a9e02337c"),
    "first" : "Alice",
    "last" : "Johnson",
    "counter" : 2
}
{
    "_id" : ObjectId("5d81c3b7a832f81a9e02337d"),
    "first" : "Bob",
    "last" : "Williams",
    "counter" : 3
}