您的位置:首页 > 数据库 > Mongodb

mongodb从内嵌数据对象中获取指定元素

2016-09-05 17:02 330 查看
在mognodb中, 如果数据结果类似如下:

{
"_id" : ObjectId("67c898c2561e44e13a580f79"),
"_class" : "com",
"vin" : "123",
"msg" : [
{
"data" : {
"limit" : "1",
"fim" : "e_GLOB1"
},
"name" : "name1"
},
{
"data" : {
"limit" : "2",
"fim" : "e_GLOB2"
},
"name" : "name2"
}
],
"timestamp" : NumberLong(1470709430)
}


如果只想返回msg数组中name=name1的元素,即从内嵌数据对象中获取指定元素,可以通过aggregate查询以及$filter操作符实现.

db.collectionname.aggregate({$match: {"msg.name": "name1"}}, {$project: {_id: 0, timestamp: "$timestamp", msg: {$filter: {input: "$msg", as: "msg", cond: {$eq: ["$$msg.name", "name1"]}}}}})


_id:0表示不返回_id字段,因为_id默认是返回的, 这里也取了timestamp字段.

返回结果如下:

{	"msg" : [
{
"data" : {
"limit" : "1",
"fim" : "e_GLOB1"
},
"name" : "name1"
}
],
"timestamp" : NumberLong(1470709430)
}


注意$filter操作符是在3.2.*版本才加上的,所以以前的版本是没有这个操作符的. 

nodejs代码:

function(d, callback) {
var db = mongojs(mongoUri);
var condition = {
"timestamp": {$gte: parseInt(d.t1), $lte: parseInt(d.t2)},
"msg.name" : d.msg_name
};
db.collection(data_table_name).aggregate({$match: condition}, {$project: {_id: 0, timestamp: "$timestamp", msg: {$filter: {input: "$msg", as: "msg", cond: {$eq: ["$$msg.name", d.msg_name]}}}}}, function(err, data) {
if(err) {
callback(err);
} else {
callback(null, data);
}
db.close();
});
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: