12

I have a data like below in my mongoDB collection. I want to count the total number or search_term on today basis.

_id:ObjectId("5b7e1d38981cdc1a7c8bb5fc")
search_term:"Baiyoke Boutique"
date:"August 23rd 2018, 9:34:32 am"

_id:ObjectId("5b7e1fa8fa27fd2754080ad9")
search_term:"Baiyoke Boutique"
date:"August 23rd 2018, 9:44:56 am"

_id:ObjectId("5b7e28314d2d0f388c1596cd")
search_term:"Baiyoke Florting Market"
date:"August 23rd 2018, 10:21:21 am"

I have tried following query. I have used moment. I am not what mistake I did.

var start = moment().startOf('day');
var end = moment().endOf('day');

history.find({
    date: {
        $gte: start,
        $lt: end
    }
    }).count().toArray(
    function (e, res) {
        if (e) callback(e)
        else callback(null, res)
});
2
  • Do you get any error? Commented Aug 23, 2018 at 10:38
  • I get history.find(...).count(...).toArray is not a function Commented Aug 23, 2018 at 10:39

4 Answers 4

14

You can try below queries in mongodb 3.6 and above

db.collection.find({
  "$expr": {
    "$gte": [{ "$dateFromString": { "dateString": "$date" }}, start.toDate() ],
    "$lt": [{ "$dateFromString": { "dateString": "$date" }}, end.toDate() ]
  }
}).count()

or with aggregation

db.collection.aggregate([
  { "$addFields": {
    "date": {
      "$dateFromString": {
        "dateString": "$date"
      }
    }
  }},
  { "$match": { "date": { "$gte": start.toDate(), "$lt": end.toDate() }}},
  { "$count": "count" }
])
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Ashh. Can you please help me. if my collection column have date="2020-12-13 17:20:00" and I want to fetch record greater than my current datetime which is "2020-12-11 00:00:00". how I can write expr in find()?
@NaisargParmar Pls ask a new question i will definitely try to help
2

You can try this

db.col.aggregate([{$addFields: {
      convertedDate: { $toDate: "$date" }
   }},
   {"$match" : 
       {"convertedDate" : 
           {"$gte" : ISODate("2018-08-23T09:34:32.000Z"),
            "$lte" : ISODate("2018-08-23T09:34:32.000Z")}
        }
    },
    {"$group" : {"_id" : null,"count" : {"$sum" : 1}}},
    {"$project" : {"_id" : 0}}
   ])

This is for Node js

var start = moment().startOf('day');
var end = moment().endOf('day');

history.aggregate([{
    $addFields: {
        convertedDate: { $toDate: "$date" }
    }
},
{
    "$match":
    {
        "convertedDate":
        {
            "$gte": start,
            "$lte": end
        }
    }
},
{ "$group": { "_id": null, "count": { "$sum": 1 } } },
{ "$project": { "_id": 0 } }
], function (err, count) {
    console.log(count)
})

5 Comments

what is your mongodb version?
AggregationCursor { pool: null, server: null, disconnectHandler: Store { s: { storedOps: [], storeOptions: [Object], topology: [Object] }, length: [Getter] }, bson: BSON {}, ns: 'ogin-test.history', cmd: { aggregate: 'history', pipeline: [ [Object], [Object], [Object], [Object] ], cursor: {} }, options: { readPreference: ReadPreference { mode: 'primary', tags: undefined },
This code is working fine for me and $toDate supports mongo version 4+
my mongodb version is 3.6.4
Should be better var start = moment().startOf('day').toDate(); and var end = moment().endOf('day').toDate();
0

Try:

history.count({date: {
    $gte: start,
    $lt: end
}}, function( err, count){
    console.log( "Number of users:", count );
})

for native mongodb driver

db.collection(collectionName).count({}, function(error, numOfDocs){
    if(error) return callback(error);
    db.close();
    callback(null, numOfDocs);
});

3 Comments

the result is coming 0 .. it should give 3 according to above example data set
How do you insert your date? String or date?
wrap start and end with ISODate -- {date: { $gte: ISODate(start), $lt: ISODate(end) }
-1

You are storing the string representation of the date. Try calling toDate() on moment object before storing into the database

1 Comment

It is not necessary if you want to keep the JSON a compatible. You can get the benefits of using an EJSON Date object by formatting the data as ISO8601 with your validation. {"lastAccess": { $gt: "2021-08-01T00:00:00.000Z }}" will work. The OP is using ObjectID, so that doesn't seem to be his goal, so obviously something is wrong with the design.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.