这是我的文档架构。
const smartpeepeeSchema = new Schema({
owner: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'User',
},
baby: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'Baby'
},
data: [
{
_id: {
autoIndex: false
},
serialNumber: {
type: String,
},
macAddress: {
type: String,
},
firmware: {
type: String,
},
createdAt: {
type: Date,
},
humidity: {
type: Number,
},
temperature:{
type:Number
},
type:{
type:String
}
}
]
});
这些存储在mongodb中的createdAt日期。
{ _id: 5c73e430ab6f3242b5c141c3,
owner: 5c73c2e039ecd63e0edfebf1,
baby: 5c73c2ea39ecd63e0edfebf2,
data:[
{createdAt: 2019-02-25T12:48:48.499Z,
temperature: 23.2891,
humidity: 1.82187,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' },
{ createdAt: 2019-02-25T12:48:48.499Z,
temperature: 62.2587,
humidity: 19.0473,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' },
{ createdAt: 2019-02-25T12:48:48.499Z,
temperature: 19.8427,
humidity: 68.2203,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' },
{ createdAt: 2019-02-25T12:48:48.499Z,
temperature: 55.5166,
humidity: 14.4124,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' }
],
__v: 0 }
我想要这样的结果吗?
{createdAt: specific date,
temperature: 23.2891,
humidity: 1.82187,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' },
{ createdAt: specific date,
temperature: 62.2587,
humidity: 19.0473,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' },
{ createdAt: specific date,
temperature: 19.8427,
humidity: 68.2203,
serialNumber: '01202117082100191',
macAddress: 'D2:6A:95:5E:48:6E',
firmware: '233',
type: 'diaper' },
**>我要检索特定日期的数据。
如果客户端向后端发送了类似“ 2019-02-24”的数据。
客户端必须获取该日期的所有数据
我该怎么办?..
首先感谢您阅读
来自外国开发商。**
答案 0 :(得分:2)
通过在日期中添加时间部分,尝试在查询中使用server
和$gte
。因此,以下范围将代表日期:
$lte
如果您输入的日期是00:00:00:000 -- 23:59:59.999
:
2019-02-24
此查询将返回所有db.collection.find({"DateField" : {$gte : ISODate("2019-02-24T00:00:00.000Z"), "$lte" : ISODate("2019-02-24T23:59:59.999Z")}})
为DateField
的文档。
编辑
为了实现所需的功能,可以运行2019-02-24
:
aggregate
当db.collection.aggregate(
[
{$unwind : "$data"}, // This will open up your array
{$match : {"data.createdAt" : {$gte : ISODate("2019-02-24T00:00:00.000Z"), "$lte" : ISODate("2019-02-24T23:59:59.999Z")}}} // This will filter to get only the date you need
]);
时,它将仅返回数组中的对象: