【问题标题】:Reformat MongoDB results from aggregate从聚合中重新格式化 MongoDB 结果
【发布时间】:2016-06-23 16:49:05
【问题描述】:

我来自 SQL 世界并从 MongoDB 开始,我仍然有点困惑...... 我有一个具有这种结构的集合

{
    "_id" : ObjectId("5769b51f675e6190119935ec"),
    "city" : "City1",
    "company" : "Company1",
    "country" : "Country1",
    "zip" : "23345",
},{
    "_id" : ObjectId("5769b51f675e6190119935ed"),
    "city" : "City1",
    "company" : "Company2",
    "country" : "Country1",
    "zip" : "1245",
},{
    "_id" : ObjectId("5769b51f675e6190119935ee"),
    "city" : "City2",
    "company" : "Company1",
    "country" : "Country1",
    "zip" : "123445",
},{
    "_id" : ObjectId("5769b51f675e6190119935ef"),
    "city" : "City1",
    "company" : "Company2",
    "country" : "Country1",
    "zip" : "1235445",
}

还有我的查询,

db.getCollection('stores').aggregate([{"$group":{"_id" : {city :"$city", company : "$company"}}}])

我正在使用 Angular 和 NodejS+Express 从 de 数据库中获取数据,并且我使用这种格式获取数据

[
    {
        _id:{
            city:"City1",
            company:"Compnay1"
        }
    },
    {
        _id:{
            city:"City1",
            company:"Company2"
        }
    },
    {
        _id:{
            city:"City2",
            company:"Compan1"
        }
    }
]

所以我想知道是否有办法在没有 _id 键的情况下获取此查询结果,

像这样:

 [
        {
            city:"City1",
            company:"Compnay1"
        },
        {
            city:"City1",
            company:"Company2"
        },
        {
            city:"City2",
            company:"Compan1"
        }
 ]

【问题讨论】:

    标签: angularjs mongodb


    【解决方案1】:

    只需在下一个管道阶段使用$project 作为聚合管道运算符:

    db.getCollection('stores').aggregate([
      {"$group":{"_id" : {city :"$city", company : "$company"}}},
      {"$project": {"city": "$_id.city", "company": "$_id.company", "_id": 0}}
    ])
    

    【讨论】:

      猜你喜欢
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多