我有Kitchen架构,其结构如下,我想对此架构进行查询查询,以获取包数组中包含特定ID和日期的包。
{
"_id" : ObjectId("58aacd498caf670a837e7093"),
"name" : "Kitchen 1",
"packages" : [
{
"package" : ObjectId("58aacd038caf670a837e7091"),
"availibility" : [
{
"date" : ISODate("2015-03-25T00:00:00.000Z"),
"count" : 20
},
{
"date" : ISODate("2016-03-25T00:00:00.000Z"),
"count" : 30
}
]
},
{
"package" : ObjectId("58aacd108caf670a837e7092"),
"availibility" : [
{
"date" : ISODate("2016-03-25T00:00:00.000Z"),
"count" : 10
}
]
}
],
"__v" : 0
}
如果我使用包ID(58aacd038caf670a837e7091)和日期(2015-03-25T00:00:00.000Z)进行查找查询,则响应应如下: -
{
"package" : ObjectId("58aacd038caf670a837e7091"),
"date" : ISODate("2015-03-25T00:00:00.000Z")
"count" : 20
}
答案 0 :(得分:0)
在mongodb:
您必须使用循环才能查看单个日期。对于所有日期,包括匹配的一个包ID,您可以这样做:
db.collection_name.find({'packages.package':ObjectId("package_id"),'packages.availability.date': ISODate("date")},{'packages.package':1, 'packages.availability':1}).pretty()
在mongoose中,我假设您已导入Kitchen架构
Kichen.find({'packages.package':"package_id",'packages.availability.date': "iso_date"}, function(err, package){
if(err)
console.log("There was an error");
if(package == null){
console.log("no package found");
} else {
//do whatever
}
});
答案 1 :(得分:0)
您可以比较循环中的值:
db.so.find().forEach(function(po){
po.packages.forEach(function(co){
co.availibility.forEach(function(o){
if(co.package=='58aacd038caf670a837e7091'
&&
String(ISODate("2015-03-25T00:00:00.000Z"))==String(o.date)
){
o.package=co.package;
printjson(o);
}
})
})
});
{
"date" : ISODate("2015-03-25T00:00:00Z"),
"count" : 20,
"package" : ObjectId("58aacd038caf670a837e7091")
}
答案 2 :(得分:0)
您可以运行使用 $filter
和 $arrayElemAt
运算符的聚合操作,以返回几个中的所需字段$project
管道步骤。
考虑以下管道:
Kitchen.aggregate([
{
"$project": {
"packages": {
"$arrayElemAt": [
{
"$filter": {
"input": "$packages",
"as": "pkg",
"cond": {
"$eq": [
"$$pkg.package",
mongoose.Types.ObjectId("58aacd038caf670a837e7091")
]
}
}
},
0
]
}
}
},
{
"$project": {
"package": "$packages.package",
"availibility": {
"$arrayElemAt": [
{
"$filter": {
"input": "$packages.availibility",
"as": "el",
"cond": {
"$eq": ["$$el.date", new Date("2015-03-25")]
}
}
},
0
]
}
}
},
{
"$project": {
"_id": 0,
"package": 1,
"date": "$availibility.date",
"count": "$availibility.count"
}
}
]).exec(function(err, docs){
if (err) throw err;
console.log(docs);
})