如何为MongoDB中的子项自动创建ObjectID

时间:2016-12-28 23:08:50

标签: mongodb json.net

我有一个创建JObject的Service1。然后我有Service2将JObject插入mongo DB。

服务1

var doc = GetDocument();
var jDoc = new JObject(
                    new JProperty("_id", doc.DocumentID),
                    new JProperty("url", doc.DocumentLink),                   
                    new JProperty("cost", null),
                    new JProperty("context", new JObject(
                        new JProperty("endTime", null),
                        new JProperty("startTime", doc.DocumentCreated))),                   
                    new JProperty("tasks", new JObject(
                        new JProperty("phase", "completed"),                        
                        new JProperty("initialTask", new JObject(                              
                                new JProperty("name",doc.DocumentName),
                                new JProperty("input", "someinput"))))));

然后我将这个jObject传递给Service2,它将它插入到mongoDB

服务2

     public async Task Create(JObject jDoc)
     {
            var collection = _mongoDatabase.GetCollection<BsonDocument>("units");
            var bDoc = BsonDocument.Parse(jDoc.ToString());
            await collection.InsertOneAsync(bDoc);
        }
    }

Service1为根文档元素创建_id。我期待Service2将文档插入mongoDb时,它会自动为_idcontexttasks之类的子属性创建initialTask,但不会为子项创建_id

问题
1 GT;如何为所有孩子自动创建_id? 2 - ;如果我们无法自动创建_id,并且只有选项是创建_id是Service1,那么我们可以在Service1中创建ObjectID而无需引用MongoDB.Deriver。请注意,只有Service2引用了MongoDB.Driver。 Service1没有引用MongoDB.Driver。 我想要_id个孩子,格式如下

"_id" : ObjectId("559b3cc8bf13a6740d7d50b0")

1 个答案:

答案 0 :(得分:0)

不使用文档对象作为参数,我找不到解决问题的好方法。

1)如果在文档对象的属性上使用属性,则可以自动生成类型_id的{​​{1}}值。您可以通过使用公共接口或具有属性的包装类来避免在Service1中引用MongoDB库。如果这不适合您,您可以尝试使用ObjectId;但是,这又要求您将有关SetOnInsert结构的信息传递给JObject方法。

2)如果您仍想使用Create,可以使用find / replace(可能使用正则表达式)或为JObject属性创建自定义数据类型并创建自定义序列化程序。以下工作按预期工作:

_id