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

在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();
    });
};



你可能感兴趣的:(MongoDB,JavaScript,nodejs学习)