Mongoose Query: compare two values on same document - node.js

How can I query a Mongo collection using Mongoose to find all the documents that have a specific relation between two of their own properties?
For example, how can I query a characters collections to find all those characters that have their currentHitPoints value less than their maximumHitPoints value? Or all those projects that have their currentPledgedMoney less than their pledgeGoal?
I tried to something like this:
mongoose.model('Character')
.find({
player: _currentPlayer
})
.where('status.currentHitpoints').lt('status.maximumHitpoints')
.exec(callback)
but I am getting errors since the lt argument must be a Number. The same goes if I use $.status.maximumHitpoints (I was hoping Mongoose would be able to resolve it like it does when doing collection operations).
Is this something that can be done within a Query? I would expect so, but can't find out how. Otherwise I can filter the whole collection with underscore but I suspect that is going to have a negative impact on performance.
PS: I also tried using similar approaches with the find call, no dice.

MongoDB 3.6 and above supports aggregation expressions within the query language:
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
https://docs.mongodb.com/manual/reference/operator/query/expr/

Thanks to Aniket's suggestion in the question's comments, I found that the same can be done with Mongoose using the following syntax:
mongoose.model('Character')
.find({
player: _currentPlayer
})
.$where('this.status.currentHitpoints < this.status.maximumHitpoints')
.exec(callback)
Notice the $where method is used instead of the where method.
EDIT: To expand on Derick's comment below, a more performance sensitive solution would be to have a boolean property inside your Mongoose schema containing the result of the comparison, and update it everytime the document is saved. This can be easily achieved through the use of Mongoose Schema Plugin, so you would have something like:
var CharacterSchema = new mongoose.Schema({
// ...
status: {
hitpoints: Number,
maxHitpoints: Number,
isInFullHealth: {type: Boolean, default: false}
}
})
.plugin(function(schema, options) {
schema.pre('save', function(next) {
this.status.isInFullHealth = (this.status.hitPoints >= this.status.maxHitpoints);
next();
})
})

mongoose.model('Character')
.find({
player: _currentPlayer, $expr: { $lt: ['$currentHitpoints', '$maximumHitpoints'] }
})
This above query means find the record which has currentHitpoints less than maximumHitpoints

Starting in MongoDB 5.0, the $eq, $lt, $lte, $gt, and $gte comparison operators placed in an $expr operator can use an index on the from collection referenced in a $lookup stage.
Example
The following operation uses $expr to find documents where the spent amount exceeds the budget:
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )

Related

mongodb get list of subdocuments that matched with list of values

my document schema goes like this
_id: kkj33h2kjkjh32jk34
events: [
{
_id: k234j3lk4k2j3h4j3j4
},
{
_id: k234j3lk4k2j3h4j3j4
},
{
_id: k234j3lk4k2j3h4j3j4
}
]
here is my query, I have a list of _ids of the subdocuments of events field and I need to get all the matched subdocuments as the response from the event field I have tried to use $in and many but failed can anyone suggest me how to do this
tried this
subarr=['fh576hgfu658uyg7h','k234j3lk4k2j3h4j3j4']
model.findOne({
clgid: req.query.clgid,
'events._id': {$in:subarr}
},{"events.$":1});
but the problem with the above code is that it is fetching the first matching subdocument. but I need all the matching subdocuments.
suggest me the right way to do this query so that I get all the matched subdocuments that match from array
The issue of your query matching only the first subdocument is the use of {"events.$":1} in your projection.
I'm not sure what you are actually intending to do.
{"events.$":1} will limit to the first (sub)document matching your query, as per the documentation of the $ operator.
Maybe you're trying only to get the _id of the subdocuments and then, please try the following:
subarr=['fh576hgfu658uyg7h','k234j3lk4k2j3h4j3j4']
model.findOne({
clgid: req.query.clgid,
'events._id': {$in:subarr}
},{"events._id":1});

Differences between $or and $in when querying Strings in MongoDB / mongoose

While building an API, I need to match documents that contain pending or active values for the key status.
When trying
args.status = {
$or: [
'active',
'pending'
]
}
I get an error: cannot use $or with string
However,
args.status = {
$in: [
'active',
'pending'
]
}
works just fine.
I would expect $or to work here. Can someone provide context on the differences between the two and why Strings require $in?
$or performs the logical OR operation on an ARRAY with more than two expressions e.g. {$or:[{name:"a"},{name:"b"}]} This query will return the record which are having either name 'a' or 'b'.
$in works on the array and return the documents which are which contains any of the field from your specified array e.g.{name:{$in:['a','b']}} This query will return the documents where name is either 'a' or 'b'.
Ideally both are doing same but just having the syntax difference.
In your case you have to modify your OR query syntax and add the condition expessions in an ARRAY.
{ $or: [
{
"args.status": "active"
},
{
"args.status": "pending"
}
]
}
Thats because $or expects array of objects. Objects that defines some filters out of which at least one needs to be match to return the result. For your particular scenario $in is the best option. Still if you wanna go with $or, the query will be like:
{
$or: [
{'args.status' : {$eq: 'active'}},
{'args.status' : {$eq: 'pending'}}
]
}
I'd suggest you stick with $in as it is the best fit for your requirement.
You can check the official docs for more details on $or
Hope this helps :)

Mongoose - get length of array in model

I have this Mongoose schema:
var postSchema = mongoose.Schema({
postId: {
type: Number,
unique: true
},
upvotes: [
{
type: Number,
unique: true
}
]
});
what the best query to use to get the length of the upvotes array? I don't believe I need to use aggregation because I only want to query for one model, just need the length of the upvotes array for a given model.
Really struggling to find this info online - everything I search for mentions the aggregation methodology which I don't believe I need.
Also, as a side note, the unique schema property of the upvotes array doesn't work, perhaps I am doing that wrong.
find results can only include content from the docs themselves1, while aggregate can project new values that are derived from the doc's content (like an array's length). That's why you need to use aggregate for this, even though you're getting just a single doc.
Post.aggregate([{$match: {postId: 5}}, {$project: {upvotes: {$size: '$upvotes'}}}])
1Single exception is the $meta projection operator to project a $text query result's score.
I'm not normally a fan of caching values, but it might be an option (and after finding this stackoverflow answer is what I'm going to do for my use case) to calculate the length of the field when the record is updated in the pre('validate') hook. For example:
var schema = new mongoose.Schema({
name: String,
upvoteCount: Number,
upvotes: [{}]
});
schema.pre('validate', function (next) {
this.upvoteCount = this.upvotes.length
next();
});
Just note that you need to do your updates the mongoose way by loading the object using find and then saving changes using object.save() - don't use findOneAndUpdate
postSchema.virtual('upvoteCount').get(function () {
return this.upvotes.length
});
let doc = await Post.findById('foobar123')
doc.upvoteCount // length of upvotes
My suggestion would be to pull the entire upvotes fields data and use .length property of returned array in node.js code
//logic only, not a functional code
post.find( filterexpression, {upvote: 1}, function(err, res){
console.log(res.upvotes.length);
});
EDIT:
Other way of doing would be stored Javascript. You can query the
upvote and count the same in mongodb side stored Javascript using
.length

Mongoose $ project

Using Mongoose 4.0.x, I need to execute the following (working) MongoDB query:
db.bookings.find(
{
user: ObjectId("10"), // I replaced the real ID
'flights.busy.from': {$gte: ISODate("2015-04-01T00:00:00Z")},
'flights.busy.to': {$lte: ISODate("2015-04-01T23:59:00Z")}
},
{
'flights.$': 1 // This is what I don't know to replicate
}
).pretty()
The Mongoose find operator does not accept a projection operator, like the MongoDB find one does.
How can I replicate the above query in Mongoose? Filtering the array once the query is returned is a solution I would like to avoid.
You want to look at the docs for Model.find, not Query.find. The second parameter can be used for field selection:
MyModel.find(
{
user: ObjectId("10"), // I replaced the real ID
'flights.busy.from': {$gte: ISODate("2015-04-01T00:00:00Z")},
'flights.busy.to': {$lte: ISODate("2015-04-01T23:59:00Z")}
},
'flights.$'
).exec(function(err, docs) {...});

Mongoose - find all documents whose array property contains a given subset?

I have a (simplified) model based on the following schema:
schema = mongoose.Schema({
foo: { type: String },
bars: [{ type: String }]
});
model = mongoose.model ('model', schema);
and I want to create an API to return all documents that contain all of the 'bars' which are provided in a comma separated list. So I have:
exports.findByBars = function (req, res) {
var barsToFind = req.body.bars.split(',');
// find the matching document
};
Does Mongoose provide an API for this or is there a query param I can pass to Model#find to get this functionality? I only want a document to be returned if its bar property contains all of the values in the barsToFind array.
There are ways to structure your query to do this, the approaches are different depending on your mongodb server version. So following on from your code:
For MongoDB version 2.6 and above, use the $all operator:
model.find({
"bars": { "$all": barsToFind }
},
And though the operator does exist for previous versions, it behaves differently so you actually need to generate an $and statement to explicitly match each entry:
var andBars = [];
barsToFind.forEach(function(bar) {
andBars.push({ "bars": bar })
});
model.find({
"$and": andBars
},
Both ensure that you only match documents that contain all of the entries in the array as you have specified, it's just that the syntax available to MongoDB 2.6 is a little nicer.

Resources