Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

405
Vistas
How to insert (push) a new object into a nested array using MongoDB C#?
{
    "_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#

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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:

  • MongoDB .NET Driver Quick Tour, see the section Updating Documents
  • $push Array Update Operator
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda