MongoDb从对象属性匹配条件的数组中select对象
我对mongoose和nodejs比较新。 而我试图在nodejs中快速的修改服务器端脚本。
我试图从mongoDb使用mongoose检索数据作为对象的数组。
这是我的模式看起来像 –
var heatmapSchema = new Schema({ vuid: String coordinates: [ { x: Number, y: Number, c: Number, timestamp: Number } ] }, {collection: collectionName} );
正如你所看到的, coordinates
是一个对象数组。 我想查询mongoDb,所以我得到这些坐标对象的数组,其中c = 1
( coordinate
c
属性等于1),即 –
[ { x: 100, y: 230, c: 1, timestamp: 1233312312 }, { x: 120, y: 240, c: 1, t: 1233313425 } ...... ]
在mongoose中实现这个最好的方法是什么?
UPDATE
我迄今得到的最接近的是使用下面的查询 –
heatmapModel.aggregate( [ { $unwind: '$coordinates' }, { $match: { 'coordinates.c': 1 } }, { $project: { '_id': 0, 'coordinates.x': 1, 'coordinates.y': 1, 'coordinates.c': 1, 'coordinates.timestamp': 1 } } ], function (err, result) { if (err) { console.log(err); process.exit(1); } console.log(result); process.exit(); } );
这给了我以下的输出 –
[ { coordinates: { x: 601, y: 165, c: 1, timestamp: 1438840800424 } }, { coordinates: { x: 484, y: 192, c: 1, timestamp: 1438840801211 } }, { coordinates: { x: 484, y: 192, c: 1, timestamp: 1438840801388 } }, { coordinates: { x: 414, y: 394, c: 1, timestamp: 1438840802378 } }, ..... ]
我如何摆脱json中不需要的coordinates
键?
heatMap.find({'coordinates.c':1}); 应该pipe用。