这是我用来处理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
进行了一些聚合实验,但是无法建立“嵌套”级别的动物/所有者/文档
答案 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"}}
])