mongodb 的项目数组内容

Project array content with mongodb

我的问题是,当我使用 MongoDB 坐标的 2D 索引时,一切正常,但 JSON 输出不是我想要的。

    var schema=new Schema({
        location:{
            type:[Number],  // [<longitude>, <latitude>]
            index:'2d',
            required:false
        }
    });

    **desired output**

    {
        "_id":"xxx",
        "longitude":18.056974411010742,
        "latitude":54.31120601701069,
    }

    **what i get**

    {
        "_id":"xxx",
        "location":[18.056974411010742,54.31120601701069]
    }


    **What i tried to do**
    db.foo.aggregate(
        {$project:{
        _id:1,
        longitude:"$location.0",
        latitude:"$location.1"
    }});

但是显然不行。我希望我对问题的解释足够好。谢谢

你需要做一个$unwind operator on the Location array first in your aggregation pipeline, then $group the resulting documents to apply the accumulator expressions $first and $last

您的聚合管道应如下所示(未经测试):

db.foo.aggregate([
    { "$unwind": "$location" },
    {
        "$group": {
            "_id": "$_id",
            "longitude": { "$first": "$location" },
            "latitude": { "$last": "$location" }
        }
    }
]);