繁体   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