繁体   English   中英

Mongodb 嵌套文档

[英]Mongodb nested document

我有这样的架构

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);

我正在 userSchema 中为此模式创建参考 ID

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

我的问题是,对于这个给定的模式,我想获取给定日期和给定用户的温度。我正在为所有用户提供 PredictionSchema 的参考 ID。我该怎么做?

  • $match你的用户ID条件
  • $lookup与预测集合并在let中传递预测 id,
  • $match预测 id 条件和日期条件
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"
    }
  }
])

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM