简体   繁体   中英

MongoDB get user which are new today

I am trying to find a user list which is new for day-1. I have written the query to find the users who arrived till the day before yesterday and the list of users arrived yesterday. Now I want minus those data how can I do that in a single aggregate function.

Function to get the list before yesterday

  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}}

    } 
])

similarly for the day-1 is as below

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}}

    } 
])

Result JSON are as below

/* 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
}

How can I find the difference.

It sounds like what you want is to get all users created yesterday (which is the 28th in this example).

 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}}

} 

])

Is this what you want?

Hi found the solution which is below
I used the group and first appearance of the Id and then filter record on date which I wanted.
The query is as below

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") } }   
}
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM