Node.js Mongodb嵌套文档
我有一个这样的模式Node.js Mongodb嵌套文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个这样的模式 var DateOnly = require('mongoose-dateonly')(mongoose); const HealthSchema = new Schema({ temprature: { type: Number, default: 0, }, date: { type:DateOnly, default: Date.now, }, }); const PredictionSchema= new mongo
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。我该如何做?
用户id条件$match
使用预测收集并在$lookup
中传递预测idlet
预测id条件和日期条件$match
提供的答案中是否有您认为无法解决您问题的内容?如果是,请对答案进行评论,以澄清哪些问题需要解决,哪些问题尚未解决。如果它确实回答了您提出的问题,那么请注意您提出的问题
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"
}
}
])