如何在2个级别上汇总并保存文档?

时间:2018-10-02 13:24:57

标签: mongodb mongoose aggregation-framework

这是我用来处理Elasticsearch的东西,但是我找不到使用MongoDB的方法。

这是动物的集合:

#region Selected
        public abstract class selected : IBqlField { }

        /// <summary>
        /// Used for selection on screens.
        /// </summary>
        [PXDBBool]
        //[PXDefault(false)]
        [PXUIField(DisplayName = "Selected")]
        public virtual bool? Selected { get; set; }
        #endregion

这是我期望的结果:

[
  { kind: "Dog", owner: "John", name: "Max" },
  { kind: "Dog", owner: "John", name: "Buddy" },
  { kind: "Dog", owner: "John", name: "Cooper" },
  { kind: "Cat", owner: "John", name: "Charlie" },
  { kind: "Dog", owner: "Peter", name: "Jack" },
]

有这样做的主意吗?我已经用{ Dog: { John: [ { kind: "Dog", owner: "John", name: "Max" }, { kind: "Dog", owner: "John", name: "Buddy" }, { kind: "Dog", owner: "John", name: "Cooper" }, ], Peter: [ { kind: "Dog", owner: "Peter", name: "Jack" }, ] } Cat: { John: [ { kind: "Cat", owner: "John", name: "Charlie" } ] } } $group进行了一些聚合实验,但是无法建立“嵌套”级别的动物/所有者/文档

1 个答案:

答案 0 :(得分:1)

您可以在3.6中使用以下汇总。

嵌套数组结构

db.colname.aggregate([
  {"$group":{"_id":{"kind":"$kind","owner":"$owner"},"docs":{"$push":"$$ROOT"}}},
  {"$group":{"_id":"$_id.kind","ownerbykind":{"$push":{"owner":"$_id.owner","docs":"$docs"}}}}
])

OR

$mergeObjects$arrayToObject结合使用以产生所需的结构。

db.colname.aggregate([
  {"$group":{"_id":{"kind":"$kind","owner":"$owner"},"a":{"$push":"$$ROOT"}}},
  {"$group":{"_id":"$_id.kind","b":{"$mergeObjects":{"$arrayToObject":[[["$_id.owner","$a"]]]}}}},
  {"$group":{"_id":null,"c":{"$mergeObjects":{"$arrayToObject":[[["$_id","$b"]]]}}}},
  {"$replaceRoot":{"newRoot":"$c"}}
])