Mongoid,按名称和编号聚合模型
Mongoid, aggregate models by name and number
我有一个名为 Shop
的模型,它有 name
、image
。有可能会有多个同名店铺。
例如,如果我有这些商店:
[{_id: "1", name: "Shop A", image: "ImageShopA.jpg"},
{_id: "2", name: "Shop A", image: "ImageShopA1.jpg"},
{_id: "3", name: "Shop B", image: "ImageShopB.jpg"},
{_id: "4", name: "Shop B", image: "ImageShopB1.jpg"},
{_id: "5", name: "Shop C", image: "ImageShopC.jpg"}]
我想得到这样的结果:
[{name: "Shop A", ids: ["1", "2"], image: "ImageShopA.jpg"},
{name: "Shop B", ids: ["3", "4"], image: "ImageShopB.jpg"},
{name: "Shop C", ids: ["5"], image: "ImageShopC.jpg"}]
它创建 JSON 个对象,这些对象具有按 name
分组的分组模型的 ID,并获取第一个找到的模型的图像。
是否可以通过聚合来做到这一点?
是的,有可能。如果您 运行 mongo shell 中的以下聚合管道具有给定的数据样本
db.collection.aggregate([
{
"$sort": {
"_id": 1
}
},
{
"$group": {
"_id": "$name",
"ids": {
"$push": "$_id"
},
"image": {
"$first": "$image"
}
}
},
{
"$project": {
"name": "$_id", "ids": 1, "image": 1
}
}
])
你会得到想要的结果:
/* 0 */
{
"result" : [
{
"_id" : "Shop C",
"ids" : [
"5"
],
"image" : "ImageShopC.jpg",
"name" : "Shop C"
},
{
"_id" : "Shop B",
"ids" : [
"3",
"4"
],
"image" : "ImageShopB.jpg",
"name" : "Shop B"
},
{
"_id" : "Shop A",
"ids" : [
"1",
"2"
],
"image" : "ImageShopA.jpg",
"name" : "Shop A"
}
],
"ok" : 1
}
您需要将其转换为适当的ruby实现
我有一个名为 Shop
的模型,它有 name
、image
。有可能会有多个同名店铺。
例如,如果我有这些商店:
[{_id: "1", name: "Shop A", image: "ImageShopA.jpg"},
{_id: "2", name: "Shop A", image: "ImageShopA1.jpg"},
{_id: "3", name: "Shop B", image: "ImageShopB.jpg"},
{_id: "4", name: "Shop B", image: "ImageShopB1.jpg"},
{_id: "5", name: "Shop C", image: "ImageShopC.jpg"}]
我想得到这样的结果:
[{name: "Shop A", ids: ["1", "2"], image: "ImageShopA.jpg"},
{name: "Shop B", ids: ["3", "4"], image: "ImageShopB.jpg"},
{name: "Shop C", ids: ["5"], image: "ImageShopC.jpg"}]
它创建 JSON 个对象,这些对象具有按 name
分组的分组模型的 ID,并获取第一个找到的模型的图像。
是否可以通过聚合来做到这一点?
是的,有可能。如果您 运行 mongo shell 中的以下聚合管道具有给定的数据样本
db.collection.aggregate([
{
"$sort": {
"_id": 1
}
},
{
"$group": {
"_id": "$name",
"ids": {
"$push": "$_id"
},
"image": {
"$first": "$image"
}
}
},
{
"$project": {
"name": "$_id", "ids": 1, "image": 1
}
}
])
你会得到想要的结果:
/* 0 */
{
"result" : [
{
"_id" : "Shop C",
"ids" : [
"5"
],
"image" : "ImageShopC.jpg",
"name" : "Shop C"
},
{
"_id" : "Shop B",
"ids" : [
"3",
"4"
],
"image" : "ImageShopB.jpg",
"name" : "Shop B"
},
{
"_id" : "Shop A",
"ids" : [
"1",
"2"
],
"image" : "ImageShopA.jpg",
"name" : "Shop A"
}
],
"ok" : 1
}
您需要将其转换为适当的ruby实现