Get all records with specified properties between a certain date range - mongodb

I am passing in two dates formatted as MM-DD-YYYY which is a date range. I need to query all records within that range and include specified fields. I've had no luck.
Part of a record in Mongo:
{
"_id": "some ID",
"date": {
"$date": "2015-06-26T13:02:12.121Z"
},
Query:
var Start = '09-07-2015'
var End = '09-14-2015'
If I do:
var query = Order.find({
date : {
$lt : End,
$gt : Start
}
});
I get the full document within the week ranges as expected. However, I want to specify the fields to return rather than full document. So I've tried using grouping and project to specify those fields:
var query = Order.aggregate(
{
$match :
{
date: {
$gte: start,
$lt: end
}
},
$group:
{
cust_ID: '$request.headers.customer_id',
wholesaler_ID: '$request.headers.wholesalerID'
}
}
);
Likewise: I've also tried it using project to get the results I want. I thought maybe it won't match on a date string like 09-07-2015, so I included the ISO date directly. Still no luck... the query comes back undefined or empty:
var query = Order.aggregate(
{
$project:
{
date: 'date',
cust_ID: '$request.headers.custID',
wholesaler_ID: '$request.headers.wholesalerID'
}
},
{
$match :
{
date: {
$gte: "2014-12-09T21:02:56.872Z",
$lt: "2015-12-09T21:02:56.872Z"
}
}
}
);

var query = Order.find({
date : {
$lt : End,
$gt : Start
}}, {cust_ID:1, wholeseller_ID:1}
);
This will work.
I just tested this using Robomongo
db.getCollection('offerdb').find({time_posted:{$gt: '2015-10-21T21:40:04+05:30', $lte:'2015-12-14T05:53:14+05:30'}},{_id:1, merchant_id:1})
Works like a charm for me.

Try this command in mongo shell
use dbname
db.collection_name.find({date: {$gte: ISODate('2015-09-07 00:00:00'), $lte: ISODate('2015-09-14 23:59:59.999999')}},{'cust_ID':1,'_id':0,'wholeseller_ID':1})

Related

How to find data between two dates in mongdb

I want to find all ipAddress "192.168.0.52" between two dates,
any help please
varMatch = { $match : { "ipAddress": "192.168.0.52"}},
varGroup = { $group: {
"_id": {timestamp:{"$auditMessages.timestamp":
{$gt: ISODate("2020-05-14T13:08:30.748Z"),
$lt: ISODate("2020-04-08T13:00:34.567Z")
}}}}},
db.compte.aggregate([varMatch,varGroup])
I have a problem in date i can't find a correct syntax fo date, however in json file I don't have after timestamp.
This is example of my DB
Thank you
You can find all documents with IP address '192.168.0.52' and timestamps between two dates by adding an additional expression to your match stage.
const matchStage = {
$match: {
ipAddress: '192.168.0.52',
'auditMessages.timestamp': {
$gt: new Date('2020-05-14T13:08:30.748Z'),
$lt: new Date('2020-04-08T13:00:34.567Z')
}
}
};
Once that's done, you can perform your grouping operation as desired.

How to update date field by removing time in mongoDB?

I have a collection of 100 records.Each record have date field like below
"created_date" : ISODate("2018-11-20T00:00:00.000Z")
I want to update each record by removing the time like below
"created_date" : "2018-11-20"
How to write a query for this kind of update
You can remove the timestamp from the date using Aggregate Query and update collection using forEach function. It may take time but it will update the collection data as per your requirement. Here is Mongo aggregation query:
db.getCollection('demo').aggregate([
{
$addFields: {
DateinString: {
$dateToString: {
format: "%Y-%m-%d",
date: "$created_date"
}
}
}
}
]).forEach(function(myDoc){
db.getCollection("demo").update({
_id: myDoc._id
}, {
$set: {
"created_date": myDoc.DateinString
}
})
})

MongoDB group by date and fill zero counts

I would like to group my search results by date. The results are then also counted.
var fromDate = new Date(req.query.fromDate);
var toDate = new Date(req.query.toDate);
global.databaseStatistic.collection(global.ARTICLEPRESS).aggregate([
{
$match: {
article: { $in: articleIdArray },
date: { $gte: fromDate, $lte: toDate }
}
},
{
$group: {
"_id": {
"date": {
$dateToString: { format: "%d.%m.%Y", date: "$date" }
}
},
"count": { $sum: 1 }
}
}
])
This works perfectly, but I would also like to show all days that have a count of zero. It should be so displayed every day within an interval, also having a count of zero. How can I do that?
as it looks very trivial - it is not.
There is no way to have a reference sequence to compare with, even $lookup cannot help as this a kind of inner join type.
The way you could have this done is a kind of post process of result-set returned to mongoose.
The steps I have in mind could be:
create array of dates from req.query.fromDate to req.query.toDate formated in the same way as in query
remove entries in array which we have in result set
merge our array with count:0 and date
sort results (if needed)
any comments welcome!

Cant group with aggregate in mongodb

I try to aggregate and group objects in mongodb by month. I basically copy query from mongo docs.
db.users.aggregate(
{
$group : {
_id: {
month : { $month : "$registrationDate" }
},
count: { $sum: 1 }
}
}
);
Type of registrationDate is date.
Short version of object in users collection.
{
"_id" : ObjectId("50ab08399b57f2be03000000"),
...
"registrationDate" : ISODate("2012-11-20T05:34:01.000Z"),
...
}
Then I get an exception
exception: can't convert from BSON type NumberDouble to Date
The problem is that you have some documents in your collection where the type of registrationDate is not a date but a double-precision floating point number. You can find these documents with db.users.find( { registrationDate: { $type:1 } } ). Fix these documents and it should work. Alternatively you can add the following step to the front of your aggregation to exclude those documents where the registrationDate is not a Date: {$match: { registrationDate: { $type:9 } } }

Why are dates in match aggregate query being ignored?

I'm trying to run an aggregation statement in my mongo db. I have a document whose structure is (at least) as follows:
{
"_id": ObjectId,
"date": ISODate,
"keywordGroupId": NumberLong,
"ranking": NumberLong,
}
I would like to run an aggregation statement that aggregates the 'ranking' field for a given 'keywordGroupId' and a given 'date' interval.
I have been trying with the following aggregate command:
{
aggregate : "KeywordHistory",
pipeline : [
{ $match: { keywordGroupId: 75 , "$date": {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}} },
{ $group: { _id: { null }, count: { $sum: "$ranking" } } }
]
}
This command executes without errors and returns a result. If I try to change the value for the 'keywordGroupId' field, the command returns a different value, so I assume that the $match statement works for that field (NumberLong). Though, if I change the 'date' range and I specify a time interval for which I don't have any data in the database, it still returns a result (I would actually expect an empty result set). So I have to assume that the $match statement is ignoring the date interval specified.
Can anyone help me with this point?
Remove the $ prefix on the $date field of your $match:
{ $match: {
keywordGroupId: 75,
date: {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}
}},
You only use the $ prefix when the field name is used in a value, not as a key.
Sometimes ISodate does not works . so in Case if you want to match date using only "one" date the best way is:---
ex:-- Let a schema be:---
var storeOrder = new Schema({
store_name:{type:String, required:true},
date :{type:Date ,default:moment(new Date()).format('YYYY-MM-DD')},
orders : [{
vegetable : String,
quantity : Number,
price:Number
}]
});
mongoose.model('storeorder',storeOrder);
now to aggregate by matching date :--
storeOrder.aggregate([$match:{date :new Date("2016-12-26T00:00:00.000Z")} ])
**It is must to use new Date("2016-12-26T00:00:00.000z") instead of Date("2016-12-26T00:00:00.000z") because Date(your_date) !== new Date(your_date).
THANK YOU
The aggregate expects a Javascript Date Object and doesn't work otherwise.
new Date();
new Date(year, month, day);
Please note the month start with 0 and not 1 (Your January is 0 and December 11)