How to use $push update modifier in MongoDB and C#, when updating an array in a document

前端 未结 3 1471
独厮守ぢ
独厮守ぢ 2021-01-01 20:56

I\'ve run the following code in mongo shell:

db.unicorns.insert({name:  \'Dunx\',  loves:  [\'grape\',  \'watermelon\']});

and now I\'ve so

相关标签:
3条回答
  • 2021-01-01 21:38

    To do this with the updated syntax and regular BsonDocuments instead of defined objects, use the following:

    var filter = Builders<BsonDocument>.Filter.Eq("name": "Aurora");
    var update = Builders<BsonDocument>.Update.Push("loves", "sugar"):
    
    // you can also use the async update method from Alex's answer here
    var result = fantasyContext.Unicorns.UpdateOne(filter, update);
    
    0 讨论(0)
  • 2021-01-01 21:43

    it should be something like this:

    unicorns.Update(Query.EQ("name", "Aurora"), Update.Push("loves", "sugar"));
    
    0 讨论(0)
  • 2021-01-01 21:47

    I would like to also illustrate how to do it using a different syntax

    var filter = Builders<Unicorn>
                 .Filter.Eq(e => e.Name, "Aurora");
    
    var update = Builders<Unicorn>.Update
            .Push<String>(e => e.Likes, like);
    
    await fantasyContext.Unicorns.FindOneAndUpdateAsync(filter, update);
    
    0 讨论(0)
提交回复
热议问题