为了账号安全,请及时绑定邮箱和手机立即绑定

mongodb内嵌数据对象有什么属性

/ 猿问

mongodb内嵌数据对象有什么属性

喵喵时光机 2019-05-31 14:02:04

mongodb内嵌数据对象有什么属性


查看完整描述

2 回答

?
千万里不及你

mognodb中, 如果数据结果类似如下:
[html] view plain copy
{
"_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操作符实现.
[html] view plain copy
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字段.
返回结果如下:
[html] view plain copy
{ "msg" : [
{
"data" : {
"limit" : "1",
"fim" : "e_GLOB1"
},
"name" : "name1"
}
],
"timestamp" : NumberLong(1470709430)
}

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

[html] view plain copy
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();
});
};





查看完整回答
反对 回复 2019-06-01
?
catspeake

{
"_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)
}


 



查看完整回答
反对 回复 2019-06-01

添加回答

回复

举报

0/150
提交
取消
意见反馈 邀请有奖 帮助中心 APP下载
官方微信