I am getting an issue for running the following aggregate query:
db.snippets.aggregate([ { '$project': { month: { '$month': '$created_at' }} } ])
The error message for the same is:
assert: command failed: { "errmsg" : "exception: can't convert from BSON type EOO to Date", "code" : 16006, "ok" : 0 } : aggregate failed
How do I get around this issue? I found a related question: MongoDB: can't convert from BSON type EOO to Date.
But it doesn't tell me how to get things done.
Date. BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future. The official BSON specification refers to the BSON Date type as the UTC datetime.
It is a 64-bit integer which represents the number of milliseconds. BSON data type generally supports UTC datetime and it is signed. If the value of the date data type is negative then it represents the dates before 1970.
Unlike systems that simply store JSON as string-encoded values, or binary-encoded blobs, MongoDB uses BSON to offer the industry's most powerful indexing and querying features on top of the web's most usable data format.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
try this one, its help for me above problem.
db.snippets.aggregate([{ '$project': { month: { $substr: ["$created_at", 5, 2] } } }]);
above code get month wise
data is entered into the database in ISO format which can then be easily worked with.
You likely have one or more docs with a created_at
value that's not a BSON Date
and you'll need to fix that by converting those values to Date
or removing them.
You can find those docs with a $not
query that uses the $type
operator like:
db.snippets.find({created_at: {$not: {$type: 9}}})
If the created_at
values are date strings, you can find the docs that need updating and then update them in the shell using code like:
db.snippets.find({created_at: {$not: {$type: 9}}}).forEach(function(doc) { // Convert created_at to a Date doc.created_at = new Date(doc.created_at); db.snippets.save(doc); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With