How to put createdAt (timestamp ) manually in MongoDB - node.js

how can I add manually createdAt (timestamp ) field in MongoDB?
db.getCollection("properties").find({})
This returns all properties and this is an example:
{
"_id" : ObjectId("5e6b3269617d327b82a71723"),
"title" : "Nice and cozy apartment",
"category" : "rent",
"town" : "London",
"price" : NumberInt(3100),
"square" : NumberInt(249),
}
What I want to achieve is a field with timestamp or information about the date when a particular property is created.
Can anybody help with this?s?

just put a key in mongoose schema
createdAt:{type: Date, default: Date.now()};
//will add automatically putt entry in db whenever document created.
and use aggregate instead of find(becoz you don't have key createdAt in old document) as ,
db.orders.aggregate([
{
$addFields: {
"createdAt": { $ifNull: ["$createdAt", Date(manually whenever created)] },
}
}
])

Related

How to add/update in array document with condition in mongoose

I need to perform the upsert operation. Below is my document structure.
I want to update the spin_details array when there is a match found with package_id but with two conditions i.e. user_id & spin_details.package_id.
If there is a match with user_id but there is no match with spin_details.package_id then some package information has to be pushed into the spin_details array. If there is no match with user_id(only) itself then it should be able to insert a new document.
{
"_id" : ObjectId("6234ffa6bd36b0e5a05ac913"),
"user_id" : ObjectId("6230e5e2b1530b407cedeb1d"),
"__v" : 0,
"is_active" : true,
"spin_details" : [
{
"package_id" : ObjectId("6230e5e2b1530b407cedeb9d"),
"spin_count" : 10,
"_id" : ObjectId("6234ffa6f390e1fafa8e215b")
},
{
"package_id" : ObjectId("6230e5e2b1530b407cedeb2a"),
"spin_count" : 25,
"_id" : ObjectId("6234ffa6f390e1fafa8e409b")
}
]
}
I can do this using multiple different queries and then based on the result value. How can I do this with a single mongoose query for this situation?

Fetched sorted API data(NodeJs &Mongoose) not getting displayed in sorted order when try display in Angular UI

I have tried to get sorted in backend & tested via postman and I am getting sorted order.
const locationInfo = await locationDetails.find(query).sort({sectionName:1});
res.json(locationInfo);
[
{ //some other keys &values
"sectionName": "Closet",
},
{
"sectionName": "Dining",
},
{
"sectionName": "Kitchen",
},
{
"sectionName": "Other",
},
{
"sectionName": "Refrigerator",
}
]
After REST call storing result to,
this.result=data;
but when I try to display the same resultant data on UI, Its not getting displayed in sorted order as well as checked in console also resultant data order got changed.
Console Data
[{
sectionName: "Refrigerator",
},
{
sectionName: "Kitchen",
},
{
sectionName: "Dining",
},
{
sectionName: "Closet",
},
{
sectionName: "Other",
}]
Note: Tried to sort from .ts file also but it is not working.
this.result.sort(function(a,b){a.sectionName-b.sectionName});
If any help would be appreciated. Thanks!
SectioName is not a valid criterion for MongoDB to sort the return result. In this case, MongoDB does not know how to sort it.
Here is an example directly from the MongoDB documentation about cursor.sort():
db.restaurants.insertMany( [
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
] );
# The following command uses the sort() method to sort on the borough field:
db.restaurants.find().sort( { "borough": 1 } )
Documents are returned in alphabetical order by borough, but the order of those documents with duplicate values for borough might not be the same across multiple executions.
.sort works best with numerical values. If you are in control of the backend and are able to change how data is stored in the database. I suggest you create a field for the creation date or just an index to indicate the order of the items.
Let's say your document looks something like this:
# Doc 1
{
sectionName: "Refrigerator",
order:1
}
# Doc 2
{
sectionName: "Refrigerator",
order:2
}
Then you can do
const locationInfo = await locationDetails.find(query).sort({order:1});
which will return you the documents sorted using the order field, and the order will be consistent.

Find object from a collection according to created date

I have a collection ticket_masters,which contain createdAt field and it store the date and time .
[
{
"_id": "5e78f2ddc0e09128e81db47a",
"NAME": "Jasin",
"PHONE": "2252545414",
"MAIL": "sdsdm#m.com",
"createdAt": "2020-03-23T17:33:17.470Z",
"updatedAt": "2020-03-23T17:33:17.470Z",
"__v": 0
}
]
Now i want find records according to createAt field from the user collection. Already tried with the following code snippet.
db.getCollection('ticket_masters').find({
"createdAt" : '2020-03-17T18:30:00.237+00:00'
})
Output :
Fetched 0 record(s) in 1ms
But zero records found as per the above code snippet.Kindly help me to resolve issues
Thank you
By specifying the Date type.
The $eq operator matches documents where the value of a field equals the specified value.
// Date and time
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt": {$eq: new Date('2020-03-17T18:30:00.237+00:00')}
}
},
])
OR
// Only Date
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt": {"$gte": new Date("2020-03-17"), $lt : new Date("2020-03-18") }
}
},
])
The dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day
Using momentjs
Example:
// start today
var start = moment().startOf('day');
// end today
var end = moment(today).endOf('day');
{ createdAt: { '$gte': start, '$lte': end }
$gt Matches values that are greater than a specified value.
$lt Matches values that are less than a specified value.
For more information: https://docs.mongodb.com/manual/reference/operator/query-comparison/
Hope this will help you.
db.getCollection('ticket_masters').find({
"createdAt" : ISODate("2020-03-17T18:30:00.237+00:00")
})
or you can try this.
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt":ISODate("2020-03-17T18:30:00.237+00:00")
}
},
])

Nodejs-mongodb: Update document structure for all documents in a collection

I have a collection data which has around 300k entries and its document looks like
{
"_id" : ObjectId("5xxx85"),
"user_id" : "1",
"name" : "test",
"user_private" : "0"
}
now i want to update all the documents in this collection and new document will look like
{
"_id" : ObjectId("5xxx85"),
"rid" : "1",
"user_name" : "test",
"is_private" : "private",
"is_moderator" : "true",
"amount" : "11111"
}
i.e i need to add new fields, update field names and check if user_private = 0 then put is_private as private or else put is_private as not_private.
I am a bit new so I am not able to get how can i do this efficiently as entries are around 300k.
Please suggest some ways, pseudo code will be really helpful
To update a document a filter criteria. Check pseudo code below and follow link to read more.
You'll need to have an existing value for user_private
db.messages.updateMany([
{ "user_private" : 0 }, // filter.
{ $set: {
"user_private" : "private",
"is_moderator" : "true"
}
}, // update.
{
upsert: true
}
]);
upserts - Creates a new document if no documents match the filter or Updates documents that match the filter based on the filter and update parameters provided.

Querying a property that is in a deeply nested array

So I have this document within the course collection
{
"_id" : ObjectId("53580ff62e868947708073a9"),
"startDate" : ISODate("2014-04-23T19:08:32.401Z"),
"scoreId" : ObjectId("531f28fd495c533e5eaeb00b"),
"rewardId" : null,
"type" : "certificationCourse",
"description" : "This is a description",
"name" : "testingAutoSteps1",
"authorId" : ObjectId("532a121e518cf5402d5dc276"),
"steps" : [
{
"name" : "This is a step",
"description" : "This is a description",
"action" : "submitCategory",
"value" : "532368bc2ab8b9182716f339",
"statusId" : ObjectId("5357e26be86f746b68482c8a"),
"_id" : ObjectId("53580ff62e868947708073ac"),
"required" : true,
"quantity" : 1,
"userId" : [
ObjectId("53554b56e3a1e1dc17db903f")
]
},...
And I want to do is create a query that returns all courses that have a specific userId in the userId array that is in the steps array for a specific userId. I've tried using $elemMatch like so
Course.find({
"steps": {
"$elemMatch": {
"userId": {
"$elemMatch": "53554b56e3a1e1dc17db903f"
}
}
}
},
But It seems to be returning a empty document.
I think this will work for you, you have the syntax off a bit plus you need to use ObjectId():
db.Course.find({ steps : { $elemMatch: { userId:ObjectId("53554b56e3a1e1dc17db903f")} } })
The $elemMatch usage is not necessary unless you actually have compound sub-documents in that nested array element. And also is not necessary unless the value being referenced could possibly duplicate in another compound document.
Since this is an ObjectId we are talking about, then it's going to be unique, at least within this array. So just use the "dot-notation" form:
Course.find({
"steps.userId": ObjectId("53554b56e3a1e1dc17db903f")
},
Go back and look at the $elemMatch documentation. In this case, the direct "dot-notation" form is all you need

Resources