Prajakta_SS
Prajakta_SS

Reputation: 1

Mongodb nested document

I have a schema like this

var DateOnly = require('mongoose-dateonly')(mongoose);

const HealthSchema = new Schema({
  temprature: {
    type: Number,
    default: 0,
  },
  date: {
    type:DateOnly,
    default: Date.now,
  },

});
const PredictionSchema= new mongoose.Schema({
  
  healtData: [HealthSchema]
  
});

module.exports = Prediction = mongoose.model("Prediction",  PredictionSchema);

I am creating referance id for this schema in userSchema

const UserSchema = new Schema({
  predictionId:{
    type: mongoose.Types.ObjectId,
    ref: "Prediction",
  }
})

My question is, for this given schema I want to fetch temperature for given date and given user.I am giving referance id to PredictionSchema for all users.How can i do so?

Upvotes: 0

Views: 54

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $match you user id condition
  • $lookup with prediction collection and pass prediction id in let,
  • $match prediction id condition and date condition
let userId = 1; // convert to object id using mongoose.Types.ObjectId(userId)
let date = new Date("2020-12-01");
let startDate = new Date(new Date(date).setUTCHours(00,00,00,000));
let endDate = new Date(new Date(date).setUTCHours(23,59,59,999));

User.aggregate([
  { $match: { _id: userId } },
  {
    $lookup: {
      from: "predictions",
      let: { predictionId: "$predictionId" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$_id", "$$predictionId"] },
            "healtData.date": {
              $gte: startDate,
              $lte: endDate
            }
          }
        }
      ],
      as: "Prediction"
    }
  }
])

Playground

Upvotes: 1

Related Questions