如何在mongo的投影中重命名查询对象中的字段?

时间:2018-01-19 08:04:25

标签: node.js mongodb mongodb-query

我的事件架构如下所示。

var Event = new Schema({
    eventName: {type: String, required: true},
    eventPlace: {
        name: {type: String, default:'Virtual'},
        location: {
            type: {type: String, default: 'Point'}, 
            coordinates: {type: Array, default: [0, 0]}
        },
    },
});

我试图使用以下函数从架构中获取数据。

    var criteria = { };
    var projection = {
        _id: 0,
        eventName: 1,
        "eventPlace.name": 1, //this statement working fine
        "$eventPlace.location.coordinates[0]": 1, //this statement not working
        "$eventPlace.location.coordinates[1]": 1 //this statement not working
    };
    var option = { }
    var query = Models.Event.find(criteria, projection, option) //here i am querying the database based on the projection and criteria
    query.exec(function (err, data) {
        if (err) {
            callback(err);
        } else {
            console.log("data", data)
            callback(null, data);
        }
    })

我想以这种格式获取数据。

[{
    latitude: 37.78825,
    longitude: -122.4324,
    placeName: dubai,
    description: nothing
},
{
    latitude: 37.78825,
    longitude: -122.4324,
    placeName: dubai,
    description: nothing
}]

所以为此,我想重命名我在查询中获得的字段。我该如何重命名查询字段并使坐标语句有效?我试图从互联网上获得一些了解,但无法根据我的要求塑造它。并且不允许使用for循环。

1 个答案:

答案 0 :(得分:1)

无法在查找投影中同时投影不同的索引。使用聚合。

 var projection = {
    "_id": 0,
    "eventName": 1,
   "eventPlace":"$eventPlace.name",
    "latitude":{$arrayElemAt:["$eventPlace.location.coordinates", 0]},
    "longitude":{$arrayElemAt:["$eventPlace.location.coordinates", 1]}
};

var query = Models.Event.aggregate([{$match:criteria},{$project:projection}])