I have a mongodb collection like this:
[{
"_id": {
"$oid": "63b79f9e5c98b4aa46719920"
},
"time": {
"$numberLong": "1672978334287"
},
"tvl": 0.005495200757897796,
"wethToken1": true
},{
"_id": {
"$oid": "63b79fad5c98b4aa46719921"
},
"time": {
"$numberLong": "1672978349046"
},
"tvl": 0.010990401515795592,
"wethToken1": true
},{
"_id": {
"$oid": "63b7a0ee5c98b4aa46719922"
},
"time": {
"$numberLong": "1672978670070"
}]
I want to query the data but i want a to param (from is aways Date.now())
So i wrote this query:
const queryTVL = async (from) => {
// const formatedFrom = NumberLong(from)
// const formatedTo = NumberLong(to)
try {
const collection = await mongoClient.db("tangle-db").collection("tvl")
const documents = await collection.find({
"time": {
"$gt": from
}
}).toArray()
let docArr = []
documents.map((data) => {
console.log(data, 'data')
docArr.push({
tvl: data.tvl,
time: data.time
})
})
console.log(docArr)
return docArr
} catch (error) {
console.log(error, 'for getLastTVL')
}
}
But docArr aways return empity, something is wrong with this block:
const documents = await collection.find({
"time": {
"$gt": from
}
Can someone give me a hint?
I believe you could specify "time.$numberLong" in your find() to find the actual number.
You need to specify NumberLong to the integer as used while inserting it:
db.collection.find({
"time": {
"$gt": NumberLong("1672978349046")
}
})
Related
i am trying to find corder data in below documents but i can not do this work if you know about how to find nested array data in below document so please find data for {corder}.
{
"_id": "63064232cf92b07e37090e0a",
"sname": "Bombay collection ",
"phone": 9963366555,
"costomer": [
{
"cname": "Ammar ",
"cphone": 919628497,
"ccity": "Palanpur",
"_id": "632ef012a9b88eb59d0210fa",
"corder": [
{
"clothType": "Pathani",
"prize": 236,
"date": "2022-09-24",
"status": "true",
"_id": "632ef078a9b88eb59d02110c"
}
],
}
],
},
and my code is id = "main document id" & obid ="cosomer id " & orid = " order id "
app.get('/getuser/:id/:obid/:orid', async (req, res) => {
try {
const id = req.params.id
const obid = req.params.obid
const orid = req.params.orid
console.log(id);
const peruserdata = await getschema.find({ 'costomer.corder': orid } ,
{ "_id": orid, "costomer.$.corder": { $elemMatch: { "_id": orid } } });
res.status(201).json(peruserdata);
} catch (error) {
console.log(error);
res.send(error)
}
})
What I have
I have a DB in MongoDB like this:
{
"_id": {
"$oid": "60ba531acbfed3545c51a49e"
},
"email": "shaswat.dharaiya#gmail.com",
"Formats": [{
"format": "AST-QC",
}],
"Series": [{
"seq": "AST-QC - 1",
},
{
"seq": "AST-QC - 2",
},
{
"seq": "AST-QD - 1",
}]
}
I am successfully getting the data from the Formats array using this query:
const pipeline = [
{ $match: { "email": email } },
{ $unwind: "$Formats" },
]
const res = await colc.aggregate(pipeline)
What I want
Along with the data in the Formats array, I need the count of every format that is used by seq in Series array.
I am certain that it can be done using $addFields, Something like this.
const pipeline = [
{ $match: { "email": email } },
{ $unwind: "$Formats" },
{ $addFields: {"Formats.count": 0} }
]
const res = await colc.aggregate(pipeline)
But I am not sure as to how.
I don't want to call another query using .count()
$filter to iterate loop of Series array
$regexMatch to search format in seb
$size to get total elements in filtered result
const pipeline = [
{ $match: { email: email } },
{ $unwind: "$Formats" },
{
$addFields: {
"Formats.count": {
$size: {
$filter: {
input: "$Series",
cond: {
$regexMatch: {
input: "$$this.seq",
regex: "$Formats.format"
}
}
}
}
}
}
}
]
Playground
I have a database of football matches and have the following situation:
Promotion >= 6 points & Relegation < 4 points.
I am in Season 1, Division 8. I have 1 match in my database that is for season 1, it was a win so 3 points.
I then have [{"season": "1", "Score": "1-0"}, {"season": "1", "Score": "2-0"}, {"season": "2", "Score": "3-0"}]
The first two matches in the array are for season 1 so I know this is division 8.
For the third match I need to check the result of Season 1 to know what division Season 2 should be. My issue is that when I check this it is only checking based on the very first match and it is saying 3 points when it should be 9 points.
How do I force Mongoose to use the latest snapshot of my database and not one from the very start of the function?
Matches.js
const router = require('express').Router();
const Match = require('../../models/match.model');
const getSeasonData = require('./getSeasonData');
router.route('/getNewMatches').post(auth, async (req, res) => {
const matches = await Match.find();
const getDivisionBasedOnSeasonResult = async () => {
const seasonData = await getSeasonData(seasonOfLastGame);
console.log({ seasonData });
switch (seasonData[0].seasonResult) {
case "Promoted":
return seasonData[0].division - 1;
case "Remained":
return seasonData[0].division;
case "Relegated":
return seasonData[0].division + 1;
default:
console.log("result not one of the three values");
}
}
const eaMatches = [{"season": "1", "Score": "1-0"}, {"season": "1", "Score": "2-0"}, {"season": "2", "Score": "3-0"}]
let seasonOfLastGame = 1;
for (const match of eaMatches) {
if (seasonOfLastGame === season) {
division = 8;
} else {
division = await getDivisionBasedOnSeasonResult();
}
seasonOfLastGame = season;
const newMatch = new Match({
division,
});
newMatch.save()
.then(() => {
res.json('Match added!')
})
.catch(err => res.status(400).json('Error: ' + err));
};
});
module.exports = router;
getSeasonData.js
const Match = require('../../models/match.model');
const getSeasonData = async seasonOfLastGame => {
const stages = [
{ "$match": { season: seasonOfLastGame } }
{
"$group":
{
"_id": "$season",
"points": {
"$sum": {
"$add": [{"$sum": { $cond: [{ $eq: ['$result', "Win"] }, 1, 0] } }]
}
},
"teamPlayed": { $sum: 1 }
}
},
{ "$sort": { "_id": 1 } },
{
"$project": {
"seasonResult":
{
$switch:
{
branches: [
{
case: {$gte: ["$points", 6] },
then: "Promoted"
},
{
case: {$gte: ["$points", 4] },
then: "Remained"
},
{
case: {$lt: ["$points", 4] },
then: "Relegated"
}
],
default: "Result not available"
}
}
},
}
]
return Match.aggregate(stages);
}
module.exports = getSeasonData;
I have fixed this by adding this
const updatedMatches = await Match.find();
into the else statement just above
division = await getDivisionBasedOnSeasonResult();
Im trying to build my $match dynamically for my MongoDB request, and when I do the simple stuff it works perfect, like this:
var matchStr = {};
matchStr.status = { "$lte": 3 };
matchStr.checkout = { $gte: Math.round(new Date(d).getTime()/1000) }
And then I run the
bookingTable.aggregate([
{
$match: {
$and: [ matchStr ]
}
}, etc....
Which gives a nice:
matchStr: {
"status": {
"$lte": 3
},
"checkout": {
"$gte": 1527669588
}
}
So thats all great, but what if I want to put something like this into the matchStr...
{ $or: [ { "managerDate": {$lte: managerLast} }, { "activityDate": {$lte: activityLast} } ] }
,
{ $or: [ { "expireDate": {$gt: oneDayBackward} }, { "status": {$lt: 9}} ] }
,
{ "status": { $in: [0, 1, 2, 9 ] } }
How can I do that?
There are multiple syntax for accessing the property of an object
var matchStr = {}
matchStr.status = { "$lte": 3 }
matchStr.checkout = { "$gte": Math.round(new Date().getTime()/1000) }
matchStr["$or"] = [
{ "managerDate": { "$lte": "managerLast" }},
{ "activityDate": { "$lte": "activityLast" }}
]
or If you want to push to $or operator
matchStr["$or"].push({ "managerDate": { "$lte": "managerLast" } })
matchStr["$or"].push({ "activityDate": { "$lte": "activityLast" } })
I have the following database structure stored in the mongoDB:
"location" : "Halifax",
"students" : [
{
"name": "Mike",
"ID": "B00123456",
"images": [
{
"image_url":"",
"image_id":""
}
]
},
{
"name": "Rinan",
"ID": "B00999999",
"images": [
{
"image_url":"",
"image_id":""
}
]
}
]
My question is: how do I push a new object to images array inside a student named Mike who has an ID of "B00123456", I know I should use mongoDB's update and set method. But I just couldn't find a way to achieve that. The result I want is:
"location" : "Halifax",
"students" : [
{
"name": "Mike",
"ID": "B00123456",
"images": [
{
"image_url":"",
"image_id":""
},
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
]
},
{
"name": "Rinan",
"ID": "B00999999",
"images": [
{
"image_url":"",
"image_id":""
}
]
}
]
Below is what I am trying using MongoDB's update and set:
// Connect and create a new doc
MongoClient.connect('mongodb://username:password#iad1- mongos0.objectrocket.com:someNode/db_name', functionb(err, db) {
if (err) {
console.dir(err);
console.log("error connected to mongodb");
} else {
var collection = db.collection('student_info_collection');
var student_name = req.body.name;
var student_id = req.body.ID;
collection.update(
{ location:"Halifax" },
{ ID:student_id}
{ name: student_name},
{$push: {
{
"images": [
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
]
}
}
}, function(err,result){
if (err)
console.log("Something's wrong");
else
res.sendStatus(200);
}
);
}
});
Any help?
The update() function is
update(selector, document[, options][, callback])
The first parameter is selector, please try this one
var student_name = req.body.name;
var student_id = req.body.ID;
collection.update(
{ location:"Halifax",
'students.ID': student_id,
'students.name': student_name},
{$push: { "students.$.images":
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
}
}, function(err,result){