Am trying to fetch and filter subdocuments in array.
The document has this structure:
{
"_id": {
"$oid": "58bc4fa0fd85f439ee3ce716"
},
"updatedAt": {
"$date": "2017-03-08T20:39:19.390Z"
},
"createdAt": {
"$date": "2017-03-05T17:49:20.455Z"
},
"app": {
"$oid": "58ae10852035431d5a746cbd"
},
"stats": [
{
"meta": {
"key": "value",
"key": "value"
},
"_id": {
"$oid": "58bc4fc4fd85f439ee3ce718"
},
"data": "data",
"updatedAt": {
"$date": "2017-03-05T17:49:56.305Z"
},
"createdAt": {
"$date": "2017-03-05T17:49:56.305Z"
}
},
{
"meta": {
"key": "value",
"key": "value"
},
"_id": {
"$oid": "58c06bf79eaf1f15aafe39d0"
},
"data": "data",
"updatedAt": {
"$date": "2017-03-08T20:39:19.391Z"
},
"createdAt": {
"$date": "2017-03-08T20:39:19.391Z"
}
}
]
}
What i want to get is the subdocuments in the stats array between two dates
I tried mongoose queries chain:
Model.findById(id)
.select('stats')
.where('stats.createdAt').gt(data-value).lt(data-value)
But the result always the full document including the all the subdocuments.
Also I tried aggregation like this:
Model.aggregate({
$match: {
'stats.createdAt': '2017-03-05T17:49:56.305Z'
}
})
The result is always null
Your result is null because '2017-03-05T17:49:56.305Z' is a String, you are looking for a Date : new Date('2017-03-05T17:49:56.305Z')
You can filter subdocuments with a date range with $unwind and $match :
var startDate = new Date('2017-03-05T17:49:56.305Z');
var endDate = new Date('2017-03-08T17:49:56.305Z');
Model.aggregate([{
$match: {
"_id": new mongoose.mongo.ObjectId("58bc4fa0fd85f439ee3ce716"),
"stats.createdAt": {
$gte: startDate,
$lt: endDate
}
}
}, {
$unwind: "$stats"
}, {
$match: {
"stats.createdAt": {
$gte: startDate,
$lt: endDate
}
}
}], function(err, res) {
console.log(res);
})
Or more straightforward with $filter :
Model.aggregate([{
$match: {
"_id": new mongoose.mongo.ObjectId("58bc4fa0fd85f439ee3ce716"),
"stats.createdAt": {
$gte: startDate,
$lt: endDate
}
}
}, {
$project: {
"stats": {
$filter: {
input: "$stats",
as: "stat",
cond: {
$and: [
{ $gte: ["$$stat.createdAt", startDate] },
{ $lte: ["$$stat.createdAt", endDate)] }
]
}
}
}
}
}], function(err, res) {
console.log(res);
})
Related
In my client I have a form that is sent and stored in Mongo. Made an aggregation to get the name of the people that selected a same place, date and time. Now I would like to create a Mongo document containing all matches as collections so whenever there is a match in place, date and time of people you can get it in a collection. This is what I have so far:
router.get('/match', async (req, res) => {
const matchs = await Forms.aggregate([
{
$group: {
_id: { Date: "$date", Time: "$time", Place: "$place" },
Data: { $addToSet: {Name: "$firstName", Surname:"$surname"}},
count: { $sum: 1 }
}
},
{
$match: {
count: { $gte: 2}
}
},
]);
res.json(matchs)
});
This is the result that I would like to store in Mongo:
{
"_id": {
"Date": "2022-04-20",
"Time": "15:00",
"Place": "Mall"
},
"Data": [
{
"Name": "Carl",
"Surname": "Man"
},
{
"Name": "Christian",
"Surname": "Max"
}
],
"count": 2
}
{
"_id": {
"Date": "2022-04-20",
"Time": "13:00",
"Place": "Restaurant"
},
"Data": [
{
"Name": "Felix",
"Surname": "Sad"
},
{
"Name": "Liu",
"Surname": "Lam"
}
],
"count": 2
}
You can use $out as the last stage in your pipeline. In the following example, matching_collection will contain the result of your pipeline.
{ $out : "matching_collection" }
https://www.mongodb.com/docs/v4.2/reference/operator/aggregation/out/
You can also check $merge, it could be helpful as well.
I have the following structure in my collection (you don't have to mind the status) :
{
"_id": {
"$oid": "5e6355e71b14ee00175698cb"
},
"finance": {
"expenditure": [
{
"status": true,
"_id": { "$oid": "5e63562d1b14ee00175698df" },
"amount": { "$numberInt": "100" },
"category": "Sport"
},
{
"status": true,
"_id": { "$oid": "5e6356491b14ee00175698e0" },
"amount": { "$numberInt": "200" },
"category": "Sport"
},
{
"status": true,
"_id": { "$oid": "5e63565b1b14ee00175698e1" },
"amount": { "$numberInt": "50" },
"category": "Outdoor"
},
{
"status": true,
"_id": { "$oid": "5e63566d1b14ee00175698e2" },
"amount": { "$numberInt": "400" },
"category": "Outdoor"
}
]
}
}
My previos command was this:
User.aggregate([
{ $match: {_id: req.user._id} },
{ $unwind: '$finance.expenditure' },
{ $match: {'finance.expenditure.status': true} },
{ $sort: {'finance.expenditure.currentdate': -1} },
{
$group: {
_id: '$_id',
expenditure: { $push: '$finance.expenditure' }
}
}
])
With this I just get every single expenditure back.
But now I want to group the expenditures by their category and sum up the amount of every single expenditure for their group.
So it should look like this:
{ "amount": 300 }, "category": "Sport" },
{ "amount": 450 }, "category": "Outdoor" }
Thanks for your help
Instead of grouping on _id field group on category field & sum amount field:
db.collection.aggregate([
{ $match: {_id: req.user._id}},
{
$unwind: "$finance.expenditure"
},
{
$match: {
"finance.expenditure.status": true
}
},
{
$sort: {
"finance.expenditure.currentdate": -1
}
},
{
$group: {
_id: "$finance.expenditure.category",
amount: {
$sum: "$finance.expenditure.amount"
}
}
},
{
$project: {
_id: 0,
category: "$_id",
amount: 1
}
}
])
Test : MongoDB-Playground
I'm trying to delete a subdocuments in array with Mongoose.
My datas :
{
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb762"
},
"spaces": [{
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb76f"
},
"name": "Building 2",
"subSpace": [{
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb771"
},
"name": "Basement"
}, {
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb770"
},
"name": "Floors"
}]
}, {
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb76c"
},
"name": "Building 4",
"subSpace": [{
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb76e"
},
"name": "Basement"
}, {
"_id": {
"$oid": "5d88dfe45feb4c06a5cfb76d"
},
"name": "Floors"
}]
}]
}
For this example, we want to delete the subSpace Floors in Building 2 with this _id : 5d88dfe45feb4c06a5cfb771
My code (in the model) :
exports.removeSubSpaceById = (subSpaceId) => {
Residence.findOneAndUpdate( { "spaces.subSpace._id": '5d88dfe45feb4c06a5cfb771' },
{ $pull:
{ spaces:
{ subSpace:
{ _id: '5d88dfe45feb4c06a5cfb771' }}}}, function(err, result) {
console.log(result);
})
};
Output : console.log : my entire document
But the subSpace/Basement (5d88dfe45feb4c06a5cfb771) is still in my document.
Thanks for your help.
Use positional operator for nested array operations. MongoDb Docs
exports.removeSubSpaceById = (subSpaceId) => {
Residence.findOneAndUpdate({ "spaces._id": '5d88dfe45feb4c06a5cfb76f' },
{
$pull:
{
"spaces.$.subSpace": { _id: "5d88dfe45feb4c06a5cfb771" }
}
}, function (err, result) {
console.log(result);
})
}
I have collection trusted contacts. I need to filter the document by the user. When I use method findOne I have a result, but when I use $match I got an empty array. I don't know why $match doesn't work for me.
Collection trusted contacts:
{
"_id": {
"$oid": "5d76008e4b98e63e58cb34cc"
},
"date": {
"$date": "2019-09-09T07:32:20.174Z"
},
"approvedTrustedContacts": [
{
"_id": {
"$oid": "5d764e411b7476462cf6b540"
},
"user": {
"$oid": "5c5ecaf6134fc342d4b1a9d5"
}
},
{
"_id": {
"$oid": "5d7750af52352918f802c474"
},
"user": {
"$oid": "5c64968cae53a8202c963223"
}
}
],
"pendingApprovalContacts": [],
"waitingForApprovalContacts": [],
"user": {
"$oid": "5d76008e4b98e63e58cb34cb"
}
},
{
"_id": {
"$oid": "5d7605f5e7179a084efa385b"
},
"date": {
"$date": "2019-09-09T07:32:20.174Z"
},
"approvedTrustedContacts": [
{
"_id": {
"$oid": "5d764e411b7476462cf6b541"
},
"user": {
"$oid": "5d76008e4b98e63e58cb34cb"
}
}
],
"pendingApprovalContacts": [],
"waitingForApprovalContacts": [],
"user": {
"$oid": "5c5ecaf6134fc342d4b1a9d5"
}
}
when I use method findOne
const user = await TrustedContacts.findOne({ user: "5d76008e4b98e63e58cb34cb" })
I have result
but when I use $match I got empty array
result1 = await TrustedContacts.aggregate([
{ $match: { user: "5d76008e4b98e63e58cb34cb" } },
]);
It Works,
const ObjectId = require('mongodb').ObjectId;
result1 = await TrustedContacts.aggregate([
{ $match: { user: ObjectId("5d76008e4b98e63e58cb34cb") } },
]);
I have invoice Model as following
{
...
"itemDetails": [
{
"item": "593a1a01bbb00000043d9a4c",
"purchasingPrice": 100,
"sellingPrice": 150,
"qty": 200,
"_id": "59c39c2a5149560004173a05",
"discount": 0
}
],
"payments": [],
"status": "PENDING",
"created": {
"$date": "2017-09-21T11:02:02.675Z"
},
...
}
Sample Invoice Document is as follows.
{
"_id": {
"$oid": "59c39c2a5149560004173a04"
},
"customer": {
"$oid": "5935013832f9fc0004fa9a16"
},
"order": {
"$oid": "59c1df8393cbba0004a0e956"
},
"employee": {
"$oid": "592d0a6238880f0004637e84"
},
"status": "PENDING",
"deliveryStatus": "PROCESSING",
"created": {
"$date": "2017-09-21T11:02:02.675Z"
},
"discount": 0,
"payments": [],
"itemDetails": [
{
"item": {
"$oid": "593a1a01bbb00000043d9a4c"
},
"purchasingPrice": 100,
"sellingPrice": 150,
"qty": 200,
"_id": {
"$oid": "59c39c2a5149560004173a05"
},
"discount": 0
}
],
"__v": 0
}
Item details Item is an object Id which refers to Item collection.
I'm writing a mongoose Aggregate query to get the sale by Item. for that I need to filter the invoice from a given date range and status does not equal to "CANCELED". for that, I have written following code
module.exports.saleByItem = (req, res) => {
let fromDate;
let toDate;
if ((req.query.fromDate && moment(req.query.fromDate, config.dateFormat, true).isValid()) && (req.query.toDate && moment(req.query.toDate, config.dateFormat, true).isValid())) {
fromDate = moment(req.query.fromDate, config.dateFormat).startOf('day');
toDate = moment(req.query.toDate, config.dateFormat).endOf('day');
}
Invoice.aggregate([
{
"$match": {
"created": {
"$gte": fromDate
? fromDate.toDate()
: undefined,
"$lte": toDate
? toDate.toDate()
: undefined
},
"status": {
"$ne": "CANCELED"
}
}
}, {
"$unwind": "$itemDetails"
}, {
"$group": {
"_id": "$itemDetails.item",
"qty": {
"$sum": "$itemDetails.qty"
},
"value": {
"$sum": {
"$multiply": [
"$itemDetails.qty", {
"$subtract": ["$itemDetails.sellingPrice", "$itemDetails.discount"]
}
]
}
},
"avarageSellingPrice": {
"$avg": {
"$subtract": ["$itemDetails.sellingPrice", "$itemDetails.discount"]
}
}
}
}, {
"$sort": {
"value": -1
}
}, {
"$lookup": {
from: "items",
localField: "_id",
foreignField: "_id",
as: "item"
}
}, {
"$unwind": "$item"
}, {
"$project": {
_id: 1,
itemName: "$item.itemName",
qty: 1,
value: 1,
avarageSellingPrice: 1
}
}
]).then(salesFigures => {
res.status(200).json(salesFigures);
}).catch((err) => {
res.status(422).json(err);
});
};
The issue is when I put today date to both dates it returns sale of today. Gives []
How to handle date ranges in $match with local time-zone?