1

Here is my exact schema:

{
  "_id" : ObjectId("4fb4fd04b748611ca8da0d48"),
  "Name" : "Categories",
  "categories" : [{
      "_id" : ObjectId("4fb4fd04b748611ca8da0d46"),
      "name" : "Naming_Conventions",
      "sub-categories" : [{
          "_id" : ObjectId("4fb4fd04b748611ca8da0d47"),
          "name" : "Namespace_Naming",
          "standards" : []
        }]
    }]
}

As you can see I have an array named "standards" nested way down in there. How would I programmatically insert in to that using the C# driver? I have tried all of the examples I have found online but none of them are working.

1 Answer 1

2

Something like the below. Obviously, if any of these are not present on the way down to it, you're going to get a null reference exception.

var doc = collection.FindOne(Query.EQ("_id", new ObjectId("4fb4fd04b748611ca8da0d48")));

var standards = doc["categories"]
    .AsBsonArray[0]
    .AsBsonDocument["sub-categories"]
    .AsBsonArray;

standards.Add(new BsonDocument());

collection.Save(doc);
Sign up to request clarification or add additional context in comments.

3 Comments

When I tried this I got several issues. var tstandards = doc["categories"] gives an cannot apply indexing to an expressions of type MongoDb.Driver.MongoCursor<MongoDB.Bson.BsonDocument> and there is no Add method available on any of the variables.
I think the issue is in var tstandards = doc["categories"], I think I understand what you are doing but I can't figure out how to do it
Do a FindOne instead. I've changed my example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.