2
{
    "_id" : "",
    "Username" : "",
    "Points" : 0,
    "CompletedAchievements" : [],
    "ActiveAchievements" : [],
    "Kudos" : [],
    "Teams" : [],
    "UserType" : "Standard"
}

Here is my record I'd like to insert into. I am trying to add the following object into the ActiveAchievements array.

{
    "_id": "my new id",
    "progress": 10
}

I wish to add this into the Active Achievements array which already exists on a record(which has a unique ID I can get it by) in my database. As well as more in the future.

How would I do this using the MongoDb.Driver? In C#

1 Answer 1

2

Assuming there is collection called users with a document's Username as "John Doe", the following code will add { "_id": "my new id", "progress": 10 } to the ActiveAchievements array field.

var collection = database.GetCollection<BsonDocument>("users");
var filter = Builders<BsonDocument>.Filter.Eq("UserName", "John Doe");
var update = Builders<BsonDocument>.Update
                                   .Push<BsonDocument>(
                                        "ActiveAchievements", 
                                        new BsonDocument("_id", "my new id").Add("progress", 10));
var result = collection.UpdateOne(filter, update);
Console.WriteLine(result.ModifiedCount); // should print 1, as one document is updated

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply, this helped a lot and solved my issue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.