我有一个位置模型集合,该模型将预订信息存储为一组对象。 我只想获取那些不在预订对象的日期存储范围之间的数据。
{
"_id": {
"$oid": "5bade0630c3a89206467f434"
},
"images": [
"https://res.cloudinary.com/dfkmhdn1s/image/upload/v1538125214/cxaarsh4gvk83khg6deo.jpg"
],
"created_at": {
"$date": "2018-09-28T07:56:11.485Z"
},
"name": "VX Resort",
"price": 856,
"address": "Nainital, Uttarakhand, India",
"zip": "244713",
"description": "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.\r\n\r\nMorbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.",
"owner": {
"$oid": "5badc9c5104ac9287c37954b"
},
"bookings": [
{
"_id": {
"$oid": "5bd935847f5eb301d822c42a"
},
"booking_from": {
"$date": "2018-10-30T00:00:00.000Z"
},
"booking_to": {
"$date": "2018-11-01T00:00:00.000Z"
}
}
],
"__v": 0
}
如何仅获取在 bookings 数组中存储的“ booking_from”和“ booking_to”日期之间用户选择的日期不同或不同的那些记录。
我的查询
db.getCollection('hostlocations').aggregate([
{ $match: {price:{$lte:900}} },
{ $project : {
"price" : "$$ROOT.price",
"bookings" : "$$ROOT.bookings",
"prefer" : "2018-10-31T00:00:00.000Z"
} },
{
$match : {
$or : [
{"prefer": {$gt:"bookings.booking_from",$lt:"booking.booking_to"}},
{"prefer": {$gte:"bookings.booking_from",$lt:"booking.booking_to"}},
{"prefer": {$gt:"bookings.booking_from",$lte:"booking.booking_to"}},
]
}
}
])
答案 0 :(得分:0)
检查以下汇总:
db.getCollection('tests').aggregate([
{ $match: {
price:{ $lte: 900 },
$or: [
{ "bookings.booking_from": {$gt: ISODate("2018-10-30T00:00:00.000Z")}},
{ "bookings.booking_to": {$lt: ISODate("2018-10-30T00:00:00.000Z")}}
]}
},
{ $project: { price: 1, bookings: 1 }}
])
检查包含多个数据的工作示例here。