Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

node.js - Query with string date format in mongodb

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)
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...