C# : How to add multiple values to an array in a single Update() statement

2,539 views
Skip to first unread message

Gareth Elms

unread,
Feb 12, 2011, 12:09:32 PM2/12/11
to mongodb-user
I want to add multiple new items to an array property in a single
Update() method, but this code fails :

var oQuery = Query.EQ( "_id", ObjectId.Parse( _id));
var oUpdate = Update.AddToSet( "colours", "red").AddToSet( "colours",
"green").AddToSet( "colours", "blue");
TestCollection.Update( oQuery, oUpdate);

The error is :

"Duplicate element names not allowed"

Obviously it doesn't like "colours" being used in three separate
called to AddToSet(). So how can I add "red", "green" and "blue" to
the "colours" array in a single Update() call?

Thanks

Ken Egozi

unread,
Feb 12, 2011, 12:28:06 PM2/12/11
to mongod...@googlegroups.com
Adding elements  to array is done through $push and $pushAll
the equivalent in the driver is Update.Push and Update.PushAll



Ken Egozi.
http://www.kenegozi.com/blog
http://www.delver.com
http://www.musicglue.com
http://www.castleproject.org
http://www.idcc.co.il - הכנס הקהילתי הראשון למפתחי דוטנט - בואו בהמוניכם



--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.


Gareth Elms

unread,
Feb 12, 2011, 12:41:36 PM2/12/11
to mongodb-user
Thanks I figured it out, I wanted to avoid duplicate values in the
array so I needed to use AddToSetEach() like this :

List<BsonValue> aBsonValues = new List<BsonValue>();
foreach( string sColour in aColours)
{
aBsonValues.Add( sColour);
}

oUpdate.AddToSetEach( "favouriteColours", aBsonValues);

On Feb 12, 5:28 pm, Ken Egozi <egoz...@gmail.com> wrote:
> Adding elements  to array is done through $push and $pushAll
> the equivalent in the driver is Update.Push and Update.PushAll
>
> Ken Egozi.http://www.kenegozi.com/bloghttp://www.delver.comhttp://www.musicglue.comhttp://www.castleproject.orghttp://www.idcc.co.il- הכנס הקהילתי הראשון למפתחי דוטנט - בואו בהמוניכם
Reply all
Reply to author
Forward
0 new messages