我想在一个时间间隔内组合数据。现在我看到下一个vaviant:
插入数据:
use mydb
db.items.insert( { name : "fakename1", created_at : 100, updated_at: 110 } )
db.items.insert( { name : "fakename1", created_at : 120, updated_at: 130 } )
db.items.insert( { name : "fakename1", created_at : 130, updated_at: 140 } )
db.items.insert( { name : "fakename2", created_at : 101, updated_at: 103 } )
db.items.insert( { name : "fakename2", created_at : 102, updated_at: 105 } )
db.items.insert( { name : "fakename2", created_at : 122, updated_at: 126 } )
我的查询:
db.items.find(
{ $and: [
{ created_at: { $gte: 100 } },
{ updated_at: { $lte: 130 }},
{ name: { $eq : "fakename1" }}
]
}
).map(function(myDoc) {
myDoc.includes_items = db.items.find(
{ $and: [
{ created_at: { $gte: myDoc.created_at } },
{ updated_at: { $lte: myDoc.updated_at } },
{ name: { $ne : "fakename1" }}
]
}).toArray();
return myDoc;
}
)
结果:
[
{
"_id" : ObjectId("58ab2f2eafc914fa3475f42f"),
"name" : "fakename1",
"created_at" : 100,
"updated_at" : 110,
"includes_items" : [
{
"_id" : ObjectId("58ab2f32afc914fa3475f432"),
"name" : "fakename2",
"created_at" : 101,
"updated_at" : 103
},
{
"_id" : ObjectId("58ab2f32afc914fa3475f433"),
"name" : "fakename2",
"created_at" : 102,
"updated_at" : 105
}
]
},
{
"_id" : ObjectId("58ab2f2eafc914fa3475f430"),
"name" : "fakename1",
"created_at" : 120,
"updated_at" : 130,
"includes_items" : [
{
"_id" : ObjectId("58ab2f32afc914fa3475f434"),
"name" : "fakename2",
"created_at" : 122,
"updated_at" : 126
}
]
}
]
但是调用 myDoc.events 需要很长时间。我想替换它,使用函数abbreviated syntax,但我不知道该怎么做。也许我应该使用$lookup (aggregation)?