MongoDB - 具有聚合的项目数组子字段

时间:2016-01-24 23:50:49

标签: mongodb aggregation-framework

有这个基本文件:

{
  "_id": "userID",
  "name": "User Name",
  "profiles": [
    {
      "level": 1,
      "bar": {
        "_id": "bar1ID",
        "name": "Bar Name"
      }
    },
    {
      "level": 1,
      "bar": {
        "_id": "bar2ID",
        "name": "Bar 2 Name"
      }
    }
  ]
}

我需要删除一些字段,然后重新分配bar字段,使其仅包含_id

{
  "_id": "userID",
  "profiles": [
    {
      "level": 1,
      "bar": "bar1ID"
    },
    {
      "level": 1,
      "bar": "bar2ID"
    }
  ]
}

与UserID匹配,并使用mongo聚合框架

1 个答案:

答案 0 :(得分:6)

使用.aggregate()方法。

管道中唯一的阶段是使用$project运算符的$map阶段。

class User < ActiveRecord::Base
    has_many :reports, dependent: :destroy
    belongs_to :organizations
end

class Report < ActiveRecord::Base
    belongs_to :user
end

class Organization < ActiveRecord::Base
    #has_many :users
end

返回:

db.collection.aggregate([
    { "$project": { 
        "profiles": { 
            "$map": { 
                "input": "$profiles", 
                "as": "profile", 
                "in": { 
                    "level": "$$profile.level",
                    "bar": "$$profile.bar._id" 
                } 
            } 
        } 
    } }
])