I need to add a value present in the "value" property of each document that createdAt is the current day, that the document has a "finished" property as true, and that the document has a "value" and "period.check_out" property.
So far, I have been able to select all documents that have the "period.check_out" property and sum the values. The problem is selecting the documents of the current day. I've tried to sort by day in many ways, but I'm not getting.
I enabled nas database models, so whenever I create a new document, it automatically adds me a createdAt, updatedAt and _v.
document example:
[
{
"_id": "1",
"client": {
"name": "raul germano"
},
"parking": {
"_id": "5d8bfe395e0a822b143fd68d",
"value": 2.59,
"name": "pro parking oficial"
},
"finished": false,
"createdAt": "2019-09-25T23:54:32.802Z",
"updatedAt": "2019-09-25T23:54:32.802Z"
},
{
"_id": "2",
"client": {
"name": "raul vitor"
},
"parking": {
"_id": "5d8bfe395e0a822b143fd68d",
"value": 2.32,
"name": "pro parking oficial"
},
"period": {
"check_in": {
"user": "caboco",
"moment": "2019-09-25T00:05:36.273Z"
},
"check_out": {
"user": "outro caboco",
"moment": "2019-09-25T00:09:56.506Z"
}
},
"hours": 0.07,
"value": 0.17,
"finished": true,
"createdAt": "2019-09-26T23:54:33.463Z",
"updatedAt": "2019-09-26T23:54:33.463Z"
},
{
"_id": "3",
"client": {
"name": "raul germano"
},
"parking": {
"_id": "5d8bfe395e0a822b143fd68d",
"value": 2.60,
"name": "pro parking oficial"
},
"finished": true,
"createdAt": "2019-09-25T23:54:33.463Z",
"updatedAt": "2019-09-25T23:54:33.463Z",
"period": {
"check_in": {
"user": "caboco",
"moment": "2019-09-25T00:05:36.273Z"
},
"check_out": {
"user": "outro caboco",
"moment": "2019-09-25T00:09:56.506Z"
}
},
"hours": 0.09,
"value": 0.23
}
]
Current query:
collection.aggregate([
{
$match: {
'period.check_out': {
$exists: true
},
createdAt: {
$gte: new Date("2019-09-24")
$lt: new Date("2019-09-25")
}
}
},
{
$unwind: '$parking'
},
{
$match: {
'parking._id': Types.ObjectId(parking_id)
}
},
{
$group: {
_id: Types.ObjectId(parking_id),
total: {
$sum: '$value'
}
}
}
])
That way he selects the last 24 hours
Based on the documents presented above, I need only the _id "1" and "2" documents to be selected. Thus resulting
Try replacing your $match with the following considering '2019-09-26' is the current date:
{
$match: {
'period.check_out': {
$exists: true
},
createdAt: {
$gte: new Date('2019-09-26'),
$lte: new Date(),
}
}
},
What you are matching is: $gte: 2019-09-24T00:00:00.000Z, $lte: 2019-09-25T00:00:00.000Z. And I don't think that would be the current date.
Instead you need to match is '2019-09-24T00:00:00.000Z' - current time.
Related
i have a problem that i cannot resolved by myself.
i have a data in mongo db and i want to update specific value
i show the code and images
what i want is to update the specific object (the min propetry)
how i can update it?
await user.findOneAndUpdate(
{
name: "sss",
id: "test1",
decibelHistory: {
$elemMatch: { config: { min: 10 } },
},
},
{
$set: { "config.$.min": 1 },
}
);
{
"_id": {
"$oid": "638b39c2d96a4ac3ebb33c6b"
},
"name": "sss",
"password": "sss",
"decibelHistory": [
{
"id": "test1",
"config": [
{
"max": 90,
"min": 10,
"avg": 35
}
]
}
],
"timeLapse": 1200,
"__v": 0
}
I have created a complex MongoDB document like this :
{
"_id": {
"$oid": "6354129e0f5b15991649fd10"
},
"orderId": "NEK-2209-06215614-79553",
"user": {
"$oid": "634d11565f254092fd666fd1"
},
"shippingAddress": {
"$oid": "6353aaf0fa6a1b0124c22532"
},
"billingAddress": {
"$oid": "6353aaf0fa6a1b0124c22532"
},
"productInfo": [
{
"seller": {
"$oid": "634d784c723ee32fc178aa7a"
},
"products": [
{
"productId": {
"$oid": "6353951e001ff50ea1a92602"
},
"quantity": 2,
"variation": "M",
"tax": 111
}
],
"price": 850,
"status": "Pending"
},
{
"seller": {
"$oid": "6354112f0f5b15991649fcfc"
},
"products": [
{
"productId": {
"$oid": "635411940f5b15991649fd02"
},
"quantity": 2,
"variation": "M",
"tax": 111
}
],
"price": 850,
"status": "Pending"
}
],
"total": 1671,
"shippingFees": 60,
"couponDiscount": 10,
"subtotal": 1721,
"paymentInfo": {
"paymentType": "Cash on Delivery"
},
"paymentMethod": "Home Delivery",
"createdAt": {
"$date": {
"$numberLong": "1666454174641"
}
},
"updatedAt": {
"$date": {
"$numberLong": "1666454174641"
}
},
"__v": 0
}
Here you can see that ProductInfo is an array. My Document structure is
id: "id"
productInfo: [
{seller: "id", ....},
{seller: "id", ....},
]
Now I have two things- id and seller
Actually here I want to do this- first, find by id, then filter productInfo by seller and update status to this particular seller. How can I do that ?
mydocument.findByIdAndUpdate(id,
//Here I have to write an update value to a particular seller from productInfo array.
, {new: true})
Please help me to do this. Can anyone help me?
**Note: Here I want to update only status value from a particular seller when matched find by document id.
You can do it with positional operator - $:
db.collection.update({
_id: ObjectId("6354129e0f5b15991649fd10"),
"productInfo.seller": ObjectId("6354112f0f5b15991649fcfc"),
},
{
"$set": {
"productInfo.$.status": "New status"
}
})
Working example
I tried to find users who are registered for that event.
So I join multiple collections shown below -
Events.aggregate([
{ $match: { category: "group_event" } },
// collection where events are scheduled
{
$lookup: {
from: "group_events",
let: { eventId: "$eventID" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$_id", "$$eventId"] },
{ $gt: ["$time", new Date()] },
],
},
},
},
// register user collection
{
$lookup: {
from: "register_events",
let: { eventId: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$eventId", "$$eventId"] } } },
],
as: "registerUsers",
},
},
],
as: "events",
},
},
{ $unwind: "$events" },
])
and the output is now comingout -
[
{
"_id": "614d6dfd82cb36be231083c9",
"trainerId": "61488dc36b7ccedbc884d20a",
"category": "group_event",
"eventID": "614d6dfc82cb36be231083c7",
"createdAt": "2021-09-24T06:19:41.268Z",
"updatedAt": "2021-09-24T06:19:41.268Z",
"__v": 0,
"events": {
"_id": "614d6dfc82cb36be231083c7",
"groupName": "group name 4",
"category": "sdfsdf",
"time": "2021-09-27T07:44:58.762Z",
"description": "description",
"day": "sunday",
"platform": "zoom",
"notes": "22",
"skills_to_learn": [
"demo"
],
"status": "pending",
"trainerId": "61488dc36b7ccedbc884d20a",
"meetingLink": "https://us05web.zoom.us/j/81660534858?pwd=cGZaODVjdWJUQWNtN243MlNiVUN0UT09",
"type": "group_event",
**isUserRegisted : true / false,**
"createdAt": "2021-09-24T06:19:41.000Z",
"updatedAt": "2021-09-24T06:19:41.000Z",
"__v": 0,
"registerUsers": [
{
"_id": "614ed6b4b8a545acb8517e85",
"userId": "614d59371d11becb8e23f536",
"eventId": "614d6dfc82cb36be231083c7",
"question": "",
"createdAt": "2021-09-25T07:58:44.939Z",
"updatedAt": "2021-09-25T07:58:44.939Z",
"__v": 0
}
]
}
}
]
which is ok for me bu just wanted to add a key: value, heighlited on obove section
isUserRegisted : true / false
i tried with $addFields but can't came up with any solution. Basically I need to retrieve arrays from registerUsers - collection and on the same time match the userId
I was able to figure out this issue.
simply I need to use $project and $filter to get the data if available and at last use $cond to return true or false
{
$project: {
root: "$$ROOT",
userFound: {
$filter: {
input: "$registerUsers",
as: "ac",
cond: {
$eq: ["$$ac.userId", mongoose.Types.ObjectId(userId)],
},
},
},
},
},
{
$project: {
_id: 0,
document: "$$ROOT",
userFound: {
$cond: {
if: { $isArray: "$userFound" },
then: {
$cond: {
if: {
$gt: [{ $size: "$userFound" }, 0],
},
then: true,
else: false,
},
},
else: false,
},
},
},
},
// merging nested object with parents
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$document.root",
{ isUserRegistered: "$userFound" },
],
},
},
},
I am trying to update the property date which is inside the object remindTime.
here is the original data
{
"_id": {
"$oid": "614d3cedfb2600340fdb28f9"
},
"date": "2021-09-23",
"title": "First test",
"description": "Going",
"remindTime": {
"date": "2021-09-23",
"time": "11:50:09 pm"
},
"isComplete": false,
"instantMessage": false,
"owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
"uuid": "0E561203-0BD0-4E15-AB17-858FFBD972D9",
"createdAt": {
"_delegate": {
"_methodName": "FieldValue.serverTimestamp"
}
},
"__v": 0
}
axios request data coming in on req.query = { _ref: '1632545954ref', owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73' }
axios request data coming in on req.body = { remindTime: { date: '2021-09-28' } }
Templates.updateMany((req.query, req.body))
.then(
(record) => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json(record);
},
(err) => res.status(400).json(err)
)
Here is the output but not what I desire
{
"_id": {
"$oid": "614d3cedfb2600340fdb28f9"
},
"date": "2021-09-23",
"title": "First test",
"description": "Going",
"remindTime": {
"date": "2021-09-24"
},
"isComplete": false,
"instantMessage": false,
"owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
"uuid": "0E561203-0BD0-4E15-AB17-858FFBD972D9",
"createdAt": {
"_delegate": {
"_methodName": "FieldValue.serverTimestamp"
}
},
"_ref": "1632545954ref",
"__v": 0
}
As you can see that the property date in remindTime was updated however it erased the time property
I am hoping to only update the date property and keep the time property as is like shown below but with updated date
{
"_id": {
"$oid": "614d3cedfb2600340fdb28f9"
},
"date": "2021-09-23",
"title": "First test",
"description": "Going",
"remindTime": {
"date": "2021-09-28",
"time": "11:50:09 pm"
},
"isComplete": false,
"instantMessage": false,
"owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
"uuid": "0E561203-0BD0-4E15-AB17-858FFBD972D9",
"createdAt": {
"_delegate": {
"_methodName": "FieldValue.serverTimestamp"
}
},
"__v": 0
}
You can use $set operator to update your date property exclusively, without loosing other fields.
req.body = { remindTime: { $set: { date: '2021-09-28' } } }
You can check below links for more detailed info:
MongoDB $set
updateMany opertors
I am using the following code to retrieve the data from mongodb. Somehow when I added the $match to the code it returns empty set. Without it I get my results fine so there is no any other error. What can be the error in $match . How can I fix it ?
This is the code in my API?
postSchemaModel.aggregate([{
"$geoNear": {
"near": { "type": "Point", "coordinates": [parseFloat(long), parseFloat(lat), ] },
"distanceField": "dist.calculated",
"maxDistance": parseInt(maxDistance),
"includeLocs": "dist.location",
"spherical": true
}
},
// mactchString,
{
"$match": {
"createdAt": {
"$gte": '2020-07-15 23:54:38.673665',
"$lt": '2020-06-15 23:54:38.673665'
}
}
},
{ "$limit": limit },
{ "$skip": startIndex },
{ "$sort": { "createdAt": -1 } },
{
"$lookup": {
"from": userSchemaModel.collection.name,
"localField": "user_id",
"foreignField": "_id",
"as": "user_id"
}
},
{
"$project": {
"post_data": 1,
"likes": 1,
"commentsCount": 1,
"post_img": 1,
"isUserLiked": 1,
"usersLiked": 1,
'exp_date': 1,
"has_img": 1,
"user_id": {
"img": "$user_id.img",
"_id": "$user_id._id",
"user_name": "$user_id.user_name",
"bday": "$user_id.bday",
"imagesource": "$user_id.imagesource",
"fb_url": "$user_id.fb_url",
},
"typology": 1,
"geometry": 1,
"category": 1,
"created": 1,
"createdAt": 1,
"updatedAt": 1,
}
},
]).then(async function(posts) {
//some code here
}
});
The following is a sample post from mongodb
What can be the error here. How can I fix it ?
Wrap the date field in new Date() similar to this
"$match": {
"createdAt": {
"$gte": new Date('2020-07-15T23:54:38.673Z'),
"$lt": new Date('2020-06-15T23:54:38.673Z')
}
}
Check this Q & A.