有这个基本文件:
{
"_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聚合框架
答案 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"
}
}
}
} }
])