[英]How to combine/merge multiple document to one c# object using C# mongo Db driver in .net core
I have three document on the mongdo DB like in below example (grand parent, parent and child document).我在 mongdo DB 上有三个文档,如下例所示(祖父文档、父文档和子文档)。 I wanted the object to include like in result using the C# mondoDB driver.
我希望 object 在使用 C# mondoDB 驱动程序的结果中包含类似的结果。 Scenario is If grand child does not have property/value (eg. gprop2,fprop2 ) then it will get the property/value from the parent/gran parent but at the same time if all document have same property(eg. "cprop1"), then the grad child will override the value from both parent and grad parent.
场景是如果孙子没有属性/值(例如 gprop2,fprop2 ),那么它将从父/祖父获取属性/值,但同时如果所有文档都具有相同的属性(例如“cprop1”) ,那么 grad 孩子将覆盖来自 parent 和 grad parent 的值。 Also grad child can have its own property("sprop2") which should include on the final result.
grad child 也可以拥有自己的属性(“sprop2”),该属性应包含在最终结果中。 I have got the final result by manually checking/copying the property/value down to child but I am looking for the efficient solution.
我通过手动检查/复制属性/值到子级得到了最终结果,但我正在寻找有效的解决方案。 Is there way to achieve it using the C# mongoDb drive in .NET core?
有没有办法在 .NET 内核中使用 C# mongoDb 驱动器来实现它?
Grand Parent Doc祖父母文件
{
"cprop1": "gval1",
"gprop2": "gval2"
"gppcrop2": "gpcval22",
"assets" : [
{
"gasset1": "gassetVal1",
"gcasset1": "gcassetVal1"
},......
]
}
Parent Doc父文档
{
"cprop1": "fval1",
"fprop2": "fval2",
"gppcrop2": "gpcval33",
"assets" : [
{
"passet1": "passetVal1",
"gcasset1": "gcassetVal2"
},.......
]
}
Child Doc儿童文档
{
"cprop1": "sval1",
"sprop2": "sval2",
"assets" : [
{
"sasset1": "sassetVal1",
"gcasset1": "gcassetVal3"
},..........
]
}
Final Result最后结果
{ {
"cprop1": "sval1",
"gprop2": "gval2",
"fprop2": "fval2",
"gppcrop2": "gpcval33",
"sprop2": "sval2",
"assets": [
{
"gasset1": "gassetVal1",
"passet1": "passetVal1"
"sasset1": "sassetVal1",
"gcasset1": "gcassetVal3"
},....
]
}
You can do this with Merge method.您可以使用 Merge 方法执行此操作。
static void Main(string[] args)
{
BsonDocument gp = new BsonDocument("cprop1", "gval1").Add("gprop2", "gval2").Add("gppcrop2", "gpcval22");
BsonDocument parent = new BsonDocument("cprop1", "fval1").Add("fprop2", "fval2").Add("gppcrop2", "gpcval33");
BsonDocument child = new BsonDocument("cprop1", "sval1").Add("sprop2", "sval2");
child.Merge(parent);
child.Merge(gp);
Console.WriteLine(child.ToJson(new MongoDB.Bson.IO.JsonWriterSettings() { Indent = true }));
}
You get你得到
{
"cprop1" : "sval1",
"sprop2" : "sval2",
"fprop2" : "fval2",
"gppcrop2" : "gpcval33",
"gprop2" : "gval2"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.