I am trying to find data between two given heights. I am storing heights data in separate Mongodb schema, in which the height's unique _id
is what I store in a user-schema
. So I do populate() in the GET Apis and all.
The problem is when I am working on the filter api like finding users based on given two heights, How can I find the users data between two input height? should I pass the two heights _id
to find ? If so may i know the method or some suggestion or Raw data like 5.1 to 6? If I pass raw data like 5.1 and 5.8 but how will I find users data because I am not storing raw data in user-schema
instead I am storing height's id.
Config Schema
const appconfigSchema = mongoose.Schema({
configValue: {
type: String,
required: true,
},
configDesc: {
type: String,
},
...
Config Sample Data
[
{
"_id": "636261302187d07f920b1174",
"configValue": "5.1",
"configDesc": "5ft 1in",
"metaDataType": "Height",
"isParent": false,
"parentPrimaryId": "636260f82187d07f920b1171",
"isActive": true,
"createdAt": "2022-11-02T12:23:12.999Z",
"updatedAt": "2022-11-02T12:23:12.999Z",
"__v": 0
}
]
User Schema
...
Height: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'appconfigs'
},
...
User Sample Data
...
"Country": "India",
"State": "Tamil Nadu",
"City": "Trichy",
"Height": "636261302187d07f920b1174",
...
So How to find users data between two given heights ? Should I pass heights Id only or heights raw data like 5.1 & 5.8, If so please teach me the method
CodePudding user response:
If you know both _id of heights and want to fetch all documents between these _ids then both ids will be enough to find data and you can find them like this.
const userData=await users.find({$and:[{"Height._id":{$gte:"smaller_id"}},{"Height._id":{$lte:"larger_id"}}]});
CodePudding user response:
I played with your use case and figured out this solution. Hope it helps.
const filteredUsers = await User.aggregate([
// Lookup to get height information from ID
{
$lookup: {
from: "configs", // Looking in the config table
localField: "Height",
foreignField: "_id",
pipeline: [{
// Convert value to double (was string)
$project: {
valueAsDouble: {$toDouble: "$configValue"}
}
}],
as: "heightLookup"
}
},
{
// Match users with condition 5.1 <= Height value <= 5.8
$match: {
"heightLookup.0.valueAsDouble": {$gte: 5.1, $lte: 5.8}
}
}
]);
// Expected output
[
{
"City": "Trichy",
"Country": "India",
"Height": "636261302187d07f920b1174",
"State": "Tamil Nadu",
"_id": 1,
"heightLookup": [
{
"_id": "636261302187d07f920b1174",
"valueAsDouble": 5.1
}
]
},
...
]