Mongodb如何按照数组中某一个对象进行查询
展开全部
mongodb中使用aggregate可以返回数组字段数组的指定索引的元素
参考语句:
{$match:{'duid':15}},
{$project:{duid:1,"default":1}},
{$unwind:"$default.styles"},
{$match:{'default.styles.status':1}},
{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
解释:
1:过滤数据{$match:{'duid':15}}
2:获取想要的列{$project:{duid:1,"default":1}}
3:获取展开后数组字段{$unwind:"$default.styles"}
4:条件查询数组元素{$match:{'default.styles.status':1}}
5:分组后保存结果{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
数据结构如下:
{
"_id" : ObjectId("55dad346ea23e7c11beefce5"),
"duid" : 11.0,
"default" : {
"style" : "普通会诊",
"alias" : "",
"money" : "0",
"styles" : [{
"code" : 1,
"style" : "普通会诊",
"alias" : "一般会诊",
"money" : 100,
"status" : 1,
"remark" : "需要患者亲自来到医院"
} {
"code" : 6,
"style" : "夜间门诊",
"alias" : "夜间门诊",
"money" : 100,
"status" : 0,
"remark" : "夜间门诊"
}, {
"code" : 7,
"style" : "其他门诊",
"alias" : "其他门诊",
"money" : 10,
"status" : 0,
"remark" : "其他门诊"
}]
}
}
参考语句:
{$match:{'duid':15}},
{$project:{duid:1,"default":1}},
{$unwind:"$default.styles"},
{$match:{'default.styles.status':1}},
{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
解释:
1:过滤数据{$match:{'duid':15}}
2:获取想要的列{$project:{duid:1,"default":1}}
3:获取展开后数组字段{$unwind:"$default.styles"}
4:条件查询数组元素{$match:{'default.styles.status':1}}
5:分组后保存结果{$group:{_id:"$_id","defaults":{$push:"$default.styles"}}}
数据结构如下:
{
"_id" : ObjectId("55dad346ea23e7c11beefce5"),
"duid" : 11.0,
"default" : {
"style" : "普通会诊",
"alias" : "",
"money" : "0",
"styles" : [{
"code" : 1,
"style" : "普通会诊",
"alias" : "一般会诊",
"money" : 100,
"status" : 1,
"remark" : "需要患者亲自来到医院"
} {
"code" : 6,
"style" : "夜间门诊",
"alias" : "夜间门诊",
"money" : 100,
"status" : 0,
"remark" : "夜间门诊"
}, {
"code" : 7,
"style" : "其他门诊",
"alias" : "其他门诊",
"money" : 10,
"status" : 0,
"remark" : "其他门诊"
}]
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询