1

i'm trying to update an item in voteResultList by matching item's 'voteId' field.

the document:

{
   voteDocumentId: "....",
   voteResultList: [
       {
           voteId: "....",
           voteResult: "NA"
       },
       {
           voteId: "....",
           voteResult: "Against"
       }
       ....
   ]
}

if in mongo i can use this command and it works correctly.

db.getCollection('VoteCollection').update({'voteDocumentId': '....', 'voteResultList.voteId': '....'},{'$set': {'voteResultList.$.voteResult': 'Approve'}})

in csharp code using csharp mongo driver, i generated a filter bson document from this json document

{'voteDocumentId': '....', 'voteResultList.voteId': '....'}

then i generated a update bson document by this code

Builders<BsonDocument>.Update.Set("voteResultList.$.voteResult", "Approve")

but apparently i'm not doing it correctly, because after calling MongoCollection.UpdateMany(filter, update), mongoUpdateResult.ModifiedCount = 0, and nothing changes in mongodb document.

so what is the correct way of doing this?

Thanks!

IPE
  • 15
  • 1
  • 4
  • Possible duplicate of [Mongo update array element (.NET driver 2.0)](https://stackoverflow.com/questions/31453681/mongo-update-array-element-net-driver-2-0) – dnickless Jun 16 '17 at 21:05

1 Answers1

2

Here's a complete working example for your case based on the answer here: Mongo update array element (.NET driver 2.0)

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Linq;

namespace ConsoleApp1
{
    public class VoteCollection
    {
        public ObjectId Id;
        public string voteDocumentId;
        public VoteResult[] voteResultList;
    }

    public class VoteResult
    {
        public string voteId;
        public string voteResult;
    }

    public class Program
    {
        public static IMongoDatabase _db;

        static void Main(string[] args)
        {
            var collection = new MongoClient().GetDatabase("test").GetCollection<VoteCollection>("VoteCollection");

            collection.InsertOne
            (
                new VoteCollection
                {
                    voteDocumentId = "foo",
                    voteResultList = new []
                    {
                        new VoteResult { voteId = "bar1", voteResult = "NA" },
                        new VoteResult { voteId = "bar2", voteResult = "Against" },
                    }
                }
            );

            var filter = Builders<VoteCollection>.Filter.Where(voteCollection => voteCollection.voteDocumentId == "foo" && voteCollection.voteResultList.Any(voteResult => voteResult.voteId == "bar1"));
            var update = Builders<VoteCollection>.Update.Set(voteCollection => voteCollection.voteResultList[-1].voteResult, "Approve");
            collection.UpdateMany(filter, update);

            Console.ReadLine();
        }
    }
}
dnickless
  • 10,733
  • 1
  • 19
  • 34