【问题标题】:Specify Return Format指定返回格式
【发布时间】:2015-04-25 20:59:29
【问题描述】:

在 mongo 中有没有一种方法可以让我指定我希望如何返回数据的格式?

如果可能,我希望能够将项目作为数组返回。让我们看看这个非常基本的例子:

{
    color: red
},
{
    color: white
},
{
    color: blue
}

所以对于这个例子,我想把上面的文档作为一个数组来获取:

{
    colors: [red, white, blue]
}

有没有办法指定如何退货?我知道我可以指定要获取哪些列,但是我必须遍历它们来构建数组。我希望 mongodb 内置了这个,因为它可能比 node、php、java 等更快。

【问题讨论】:

    标签: mongodb projection


    【解决方案1】:

    使用 aggregation framework。聚合管道将简单地具有 $group 操作,其中 $addToSet 操作符将值添加到数组中。例如,对于包含示例文档的集合:

    /* 1 */
    {
        "_id" : ObjectId("553c0101dddf8dcf96bdcdea"),
        "color" : "red"
    }
    
    /* 2 */
    {
        "_id" : ObjectId("553c0101dddf8dcf96bdcdeb"),
        "color" : "white"
    }
    
    /* 3 */
    {
        "_id" : ObjectId("553c0101dddf8dcf96bdcdec"),
        "color" : "blue"
    }
    

    以下聚合

    db.collection.aggregate([
        {
            "$group": {
                "_id": 0,
                "colors": {
                    "$addToSet": "$color"
                }
            }
        },
        {
            "$project": {
                "_id": 0,
                "colors": 1
            }
        }
    ])
    

    将产生所需的输出:

    /* 1 */
    {
        "result" : [ 
            {
                "colors" : [ 
                    "blue", 
                    "white", 
                    "red"
                ]
            }
        ],
        "ok" : 1
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多