How do i append timestamp to a field in Mongo DB - mongodb

I have a document with below fields inside a mongo collection.
{
_id: policyId_YYYYMMDDHH24MISS,
createDate: ISO DATE,
createId: VARCHAR
}
how can i append timestamp 'YYYYMMDDHH24MISS' to a field?
Expected:
{
_id: CERT00501_20160210132745,
createDate: ISO DATE,
createId: abcd1234
}

Well, you really don't need to store timestamp in MongoDB as it's default _id field do this for you.
However, if you have special needs, you can store timestamp as number in MongoDB.
// in javascript
var id = "CERT00501_"+ Date.now();
var doc = {
_id: id,
createDate: "2012-12-19T06:01:17.171Z",
createId: ""
}
You'll get a document as below:
{
_id: 'CERT00501_1457373601773',
createDate: '2012-12-19T06:01:17.171Z',
createId: ''
}
Please see more documentation about ObjectId.

Related

Groupby createdAt in prisma to get data for each date

So the prisma is grouping the createdAt feild as an unique entity not by comparing the actual date of it. Like this is the answer for the group by query but all the dates in result are the same but the time is different, I can i get all the data for a perticular date
[
{ createdAt: 2023-01-20T08:15:35.846Z },
{ createdAt: 2023-01-20T08:15:35.848Z },
{ createdAt: 2023-01-20T08:15:35.847Z }
]

How to ignore schema default value when querying in mongoose?

eg.
created: {
type: Date,
default: Date.now,
}
, but in mongodb there exists some old data without "created" field. How can I get real data but not Date.now.
We can use $exists here to fetch the new documents which will have the created field.
Mongo Shell Query
db.collection.find( { created: { $exists: true} } )

Get newest object of each subset

I'm working on an app based on mongodb and mongoose. One of my schemas has the following form:
var schema = new mongoose.Schema(
{
name: { type: String },
timestamp: { type: Number, default: Date.now },
// further properties
});
schema.index({ name: 1, timestamp: -1 });
I'd like to retrieve the newest object (i.e., largest timestamp) for a set of name-strings.
E.g., consider the set of names ['a','b']. How do I query the database such that I get returned a collection of objects that contains both, the newest entry where id=='a', and the newest entry where id=='b'?
[Update: The idea is to avoid having to query the database multiple times (i.e. once for each name).]
"How do I query the database such that I get returned a collection of objects that contains the newest where id=='a'"
db.collection.find({ name : 'a' }).sort({ timestamp : -1 })
"and the newest entry where id=='b'?"
db.collection.find({ name : 'b' }).sort({ timestamp : -1 }).limit(1)

MongoDB ObjectId

I am having these schemas:
//first
{
books: Number,
author: String
}
//second
{
book_id: ObjectId,
price: Number,
name: String
}
Now that any document has unique _id I want to take the _id from the first document and assign it to book_id from second document so I can find it later by:
db.collection.find({_id: user_id})
Do I have to use as a type of book_id : ObjectId and if I have to how should I continue ?

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)