Node.js moongoose convert to spring mongotemplate - node.js

I have a code like this created with node.js and mongoose:
let data = { buy: [], sell: [] };
let buy = await Orders.aggregate([
{
$match: {
status: "Open",
instrument: instrument,
bidType: "buy",
},
},
{ $group: { _id: "$price", amount: { $sum: "$amount" } } },
{ $sort: { _id: -1 } },
{ $limit: 100 },
]);
I want to do this using springboot and mongodb. I tried many ways but couldn't.I will be
grateful if you could help me

Related

aggregate query in mongoose mongodb nodejs

Hi I am trying the below query in my nodejs code
const totalCount = await model.countDocuments({
'createdAt': { $gte: new Date(startDate), $lte: new Date(endDate) },
}).exec();
const activeCount = await model.countDocuments({
'createdAt': { $gte: new Date(startDate), $lte: new Date(endDate) },
'enabled': true,
}).exec();
const inactiveCount = (totalCount - activeCount);
return { totalCount, activeCount, inactiveCount };
Is there any way i can combine the above in a single query using aggregate in mongoose? Kindly guide me to the best solution .
Yes, quite simple using some basic operators, like so:
model.aggregate([
{
$match: {
createdAt: {
$gte: new Date(startDate),
$lte: new Date(endDate)
}
}
},
{
$group: {
_id: null,
totalCount: {
$sum: 1
},
activeCount: {
$sum: {
$cond: [
{
$eq: [
"$enabled",
true
]
},
1,
0
]
}
}
}
},
{
$project: {
_id: 0,
totalCount: 1,
activeCount: 1,
inactiveCount: {
$subtract: [
"$totalCount",
"$activeCount"
]
}
}
}
])
Mongo Playground

I want to write a MongoDB query in NodeJS where it return the matching documents as well as the count of documents too

I want to write a MongoDB query in NodeJS where it return the matching documents as well as the count of documents too. For ex consider the below code -
const result = await Student.aggregate(
[
{
$match: {
...filter
}
},
{
$project: {
_id: 1,
payment: 1,
type: 1,
BirthDate: 1
}
},
{
$sort: { StudentData: -1 }
},
{
$count: 'count'
},
{
$skip: skip
},
{
$limit: limit
}
]
);
Here I want to save two things in the result variable - the number of documents and individually all the documents.
let [{ totalItems, result }] = await Student.aggregate(
[
{
$match: {
...filter
}
},
{
$project: {
_id: 1,
payment: 1,
type: 1,
BirthDate: 1
}
},
{
$facet: {
result: [
{
$sort: { BirthDate: -1 },
},
{
$skip: skip
},
{
$limit: limit
}
],
totalItems: [{ $count: 'count' }]
}
},
{
$addFields: {
totalItems: {
$arrayElemAt: ["$totalItems.count", 0]
},
}
}
]
);

aggregate query taking long time. How we can improve performance

We are fetching data from applicant and ticket collection. applicant collection has 19000 records and ticket collection has 10000 records.
Please suggest how to improve the performance of the below query. Thanks in advance.
totalData = await applicantObj.aggregate([
{
$match: findApplicantCriteria
},
{
$lookup: {
from: 'tickets',
let: { applicant_id: '$_id' },
pipeline: [
{
$match: {
$expr:
findCriteria
}
}
],
as: 'tickets'
}
},
{
$project: {
_id: 0,
id: "$_id",
name: "$F_First_name",
phoneNumber: "$F_R_Mobile_no",
email: "$F_Email_id",
crn: "$Reg_No",
generatedTickets: { $size: "$tickets" },
}
},
{
$match: { generatedTickets: { "$gt": 0 } }
},
{
$count: "total"
}
])

using date in $match not working in my javascript code, (node.js)

I'm trying to make a query in my javascript code, when I try to execute the query it in robo3t it works, but when I try it in my angular code, it doesn't can you please help me?
Here is the code in robo3t.
db.getCollection('interviews').aggregate({
$match: {
status: {
$ne: 'Callback'
},
dateInserted: {
$gte: ISODate("2019-02-07 00:00:00"),
$lte: ISODate("2019-02-08 00:00:00")
},
'insertedBy.adminId': '5c353f840fe0fd000440df01'
}
},
{
$group: {
_id: {
insertedBy: '$insertedBy.email'
},
timeExported: {$first: '$dateInserted'},
total: {
$sum: 1
}
},
},
{
$limit: 100
}
)
and the result shows:
result image
Now here is my code in angular
query = [{
$match: {
status: {
$ne: 'Callback'
},
dateInserted: {
$gte: new Date("2019-02-07 00:00:00").toISOString(),
$lte: new Date("2019-02-08 00:00:00").toISOString()
},
'insertedBy.adminId': localStorage.getItem('_lgu_')
}
},
{
$group: {
_id: {
insertedBy: '$insertedBy.email'
},
timeExported: {$last: '$dateInserted'},
total: {
$sum: 1
}
},
},
{
$limit: 100
},
{
$sort: {
total: 1
}
}
]
Now when I try the query in angular, it doesn't give any result and when I remove the date condition:
dateInserted: {
$gte: new Date("2019-02-07 00:00:00").toISOString(),
$lte: new Date("2019-02-08 00:00:00").toISOString()
},
It will give a result but not what I am expecting.

Aggregate and Sort Documents based on array element date time and field

Currently I have the following schema:
User:{
verified:boolean,
history:[{
type:string,
dateTime:datetime
}]
}
I need to aggregate and sort the data based on the history.type and history.datetime. For example, I have 100 documents. Half of it have history.type="Testing" and each of the history have its own datetime.
I need to match the history type and sort the datetime using mongoose nodejs.
Here is what I did but didn't work as expected:
let user = await User.aggregate([
{
$match: {
"nameVerified":true,
'history.type' : 'NAME_VERIFIED'
}
},
{$unwind: '$history'},
{
$match: {
'history.type' : 'NAME_VERIFIED'
}
},
{
$group : {
_id :'$_id'
}
},
{
$sort:
{
'history.dateTime': -1
}
}]);
Sample Data:
{_id:1,verified:false,history:[...]}
{_id:2,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-23},{type:"TEST",dateTime:2018-10-25}]}
{_id:3,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-24},{type:"TEST",dateTime:2018-10-21}]}
{_id:4,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-21},{type:"TEST",dateTime:2018-10-21}]}
{_id:5,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-22},{type:"TEST",dateTime:2018-10-21}]}
Expected results:
{_id:3,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-24},{type:"TEST",dateTime:2018-10-21}]}
{_id:2,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-23},{type:"TEST",dateTime:2018-10-25}]}
{_id:5,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-22},{type:"TEST",dateTime:2018-10-21}]}
{_id:4,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-21},{type:"TEST",dateTime:2018-10-21}]}
Anyone can suggest a solution?
The following query will return array of documents with matching history.type and sorted by history.dateTime.
User.aggregate([{
$match: {
"history.type": 'NAME_VERIFIED',
}
},
{
$unwind: '$history'
},
{
$match: {
"history.type": 'NAME_VERIFIED',
}
},
{
$sort: {
'history.dateTime': -1
}
},
{
$group: {
'_id': {
'_id': '$_id',
'verified': '$verified'
},
'history': {
'$push': '$history'
}
}
},
{
$project: {
'_id': '$_id._id',
'verified': '$_id.verified',
'history': 1
}
}
])
If anything should be changed in criteria, please let me know, I will try to reshape the query.
Finally I found a solution as follow:
User.aggregate([
{
$match: {
"nameVerified":true,
"history.type": 'NAME_VERIFIED',
}
},
{
$unwind: '$history'
},
{
$match: {
"nameVerified":true,
"history.type": 'NAME_VERIFIED',
}
},
{
$sort: {
'history.dateTime': -1
}
},
{
$group: {
_id: '$_id',
'history': {
'$push': '$history'
}
}
},
{
$sort: {
'history.dateTime': -1
}
},
{
$skip: skipNo
},
{
$limit: limitNo
}
])

Resources