Im actually new to MongoDB, I need to create a query that could find values in between 10 and 500 in 'quantity' field. But the 'quantity' is of type string .
The below code snipet shows my Inventory Model(which contains the quantity field of type string)
const inventorySchema = mongoose.Schema({
email: {type: String , require:true},
name: {type: String , require:true},
quantity: {type: String , require:true}, //The quantity field is of type string
batchId: {type: String , require:true},
expireDate: {type: Date , require:true},
price: {type: String , require:true},
imagePath : { type: String , require: true}
})
I used the below mongoDB expression query using $lte and $gte operations but this didn't work . It gave me an error stating "An object representing an expression must have exactly one field"
const postQuery = Inventory.find({ $expr: {
$lte: [ { $toDouble: "$quantity" }, 500.0 ],
$gte: [ { $toDouble: "$quantity" }, 10.0 ] }
});
Yes because $expr
support one expression field at a time, you can try this way,
Inventory.find({
$and:[
// GT FIRST
{$expr: { $gte: [ { $toDouble: "$quantity" }, 10.0 ] } },
// LT LAST
{$expr: { $lte: [ { $toDouble: "$quantity" }, 500.0 ]} }
]
});
With $and we can use 2 separate expressions