簡體   English   中英

MongoDB 獲取今天新的用戶

[英]MongoDB get user which are new today

我正在嘗試查找第 1 天的新用戶列表。 我寫了查詢來查找前天到達的用戶和昨天到達的用戶列表。 現在我想減去這些數據,我怎么能在單個聚合 function 中做到這一點。

Function 獲取前天名單

  db.chat_question_logs.aggregate([
    {  
        $match : {"createdDate":{$lte: ISODate("2020-04-29T00:00:00Z")}}
    },
    {
        "$project" :
        {
           _id : 0,
            "userInfo.userId":1
        }
    },
    { 
        "$group": {
        "_id": {userId:"$userInfo.userId"},"count": {$sum : 1}}

    } 
])

同樣的第 1 天如下

db.chat_question_logs.aggregate([
    {  
        $match : {"createdDate":{$gte: ISODate("2020-04-30T00:00:00Z"),$lte: ISODate("2020-05-01T00:00:00Z")}}
    },
    {
        "$project" :
        {
           _id : 0,
            "userInfo.userId":1
        }
    },
    { 
        "$group": {
        "_id": {userId:"$userInfo.userId"},"count": {$sum : 1}}

    } 
])

結果 JSON 如下

/* 1 */
{
    "_id" : {
        "userId" : "2350202241750776"
    },
    "count" : 1
},

/* 2 */
{
    "_id" : {
        "userId" : "26291570771793121"
    },
    "count" : 1
},

/* 3 */
{
    "_id" : {
        "userId" : "2742872209107866"
    },
    "count" : 5
},

/* 4 */
{
    "_id" : {
        "userId" : "23502022417507761212"
    },
    "count" : 1
},

/* 5 */
{
    "_id" : {
        "userId" : "2629157077179312"
    },
    "count" : 43
}

我怎樣才能找到不同之處。

聽起來您想要的是讓所有用戶在昨天創建(在本例中是 28 日)。

 db.chat_question_logs.aggregate([
{  
    $match : { $and: [ 
        { "createdDate":{$lt: ISODate("2020-04-29T00:00:00Z")} },
        { "createdDate": {$gte: ISODate("2020-04-28T00:00:00Z") }}
    ] }
},
{
    "$project" :
    {
       _id : 0,
        "userInfo.userId":1
    }
},
{ 
    "$group": {
    "_id": {userId:"$userInfo.userId"},"count": {$sum : 1}}

} 

])

這是你想要的嗎?

嗨找到了下面的解決方案
我使用了 ID 的組和首次出現,然后在我想要的日期過濾記錄。
查詢如下

db.chat_question_logs.aggregate([
{
    $group:
     {
       _id: "$userInfo.userId",
       firstApprance: { $first: "$createdDate" }
     }   
},
{   
    $match : { "firstApprance": { $gte: new ISODate("2020-05-03"), $lt: new ISODate("2020-05-05") } }   
}
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM