Search code examples
c#mongodbmongodb-.net-driver

how to push an element into array in in mongodb .net driver


I have data looks like below

> db.people.findOne({"Name":"Jones"})
{
        "_id" : ObjectId("551dcbdc360fbd77107f8a37"),
        "Name" : "Jones",
        "Age" : 30,
        "Profession" : "Hacker"
}

The classes is defined as

class Person
{
  public ObjectId Id { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
  public List<string> Colors { get; set; }
  public List<Pet> Pets { get; set; }
}

class Pet
{
  public string Name { get; set; }
  public string Type { get; set; }
} 

And I try to push Pet element into Pets field

  var pet = new Pet
  {
    Name = "Boneless",
    Type = "Gold Fish",
  };

  var result = await coll_t.UpdateOneAsync(Builders<Person>.Filter.Eq("Name", "Jones"), Builders<Person>.Update.Push(x => x.Pets, pet)); 

  Console.WriteLine(string.Format("MatchedCount = {0}; ModifiedCount = {1}; UpsertedId = '{2}';"), result.MatchedCount.ToString(), result.ModifiedCount.ToString(), result.UpsertedId.ToString());

The update gives no error. But it didn't update. the MatchedCount in the result is 0 and ModifiedCount is also 0. What did I miss?

thanks,

PS. the Console.WriteLine(....) does not show anything it looks like it encountered an error uncaught. Any idea?


Solution

  • If MatchedCount is 0, it means the record wasn't found. Is coll_t correct? You are working against the correct database and collection?

    Try updating against your key instead of Name. Replace your filter with this:

    Builders<Person>.Filter.Eq("_id", new ObjectId("551dcbdc360fbd77107f8a37"))
    

    Also, I would initialize your Pets collection in Person, so your database knows it's an empty collection when you have no Pets.

    public Person()
    {
        Pets = new List<Pet>();
    }