Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find objects created in last week in mongo

I have a collection which has a field called timestamp containing date object. I have this query:

db.articles.find({
    timestamp:{
       '$lte':new Date(),
       '$gte': //Something to get the last week's date
    }
})

Also if it is possible, Can I sort these returned documents by length of an array in this document. Here is the schema:

section: String,
title: String,
abstract: String,
url: String,
image: {
    url: String,
    caption: String
},
votes:{
    up: [ObjectID],
    down: [ObjectID]
},
comments:[ObjectID],
timestamp: Date

I want to sort the returned objects by size of difference of votes.up and votes.down. Right now I am sorting the returned objects in Javascript where this actually returns the data.

like image 384
Ayush Gupta Avatar asked Oct 18 '15 05:10

Ayush Gupta


People also ask

How do I get the last object in MongoDB?

To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

What is $Not in MongoDB?

$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> . This includes documents that do not contain the field .


2 Answers

Seems the solution should look like

db.articles.find({
    timestamp: {
        $gte: new Date(new Date() - 7 * 60 * 60 * 24 * 1000)
    }
});
like image 52
Sergey Mell Avatar answered Sep 29 '22 14:09

Sergey Mell


it will return the previous week data i.e.,from sunday to saturday of previous week which is local where sunday is a starting day.

        { 
          $match: {
            createdAt: { 
              $gte: moment().day(-7).toDate(),
               $lt: moment().startOf('week').toDate()
            },
          }
        }
      ]);
like image 27
sai krishna Avatar answered Sep 29 '22 15:09

sai krishna