C# driver: Cannot apply $addToSet modifier to non-array

1,907 views
Skip to first unread message

Daniel Harman

unread,
Jul 2, 2011, 3:26:08 PM7/2/11
to mongodb-user
Hi guys,

Can anyone please advise? I'm trying to add a value to an arrary in a
findandmodify, but get the following error message:

Cannot apply $addToSet modifier to non-array

The update is:

MongoCollection<Account> _accounts; // initialised elsewhere...

_accounts.FindAndModify(
Query
.EQ("_id", accountId),
null,
Update
.Set("Status", AccountStatus.Validated)
.AddToSet("Roles", Roles.VALIDATED)
);

The object is serialised as:

{ "_id" : ObjectId("4e0f5677f8419321981bd873"), "Status" : 2,
"Email" : "te...@gmail.com", "HashedPassword" : "$2a
$10$TbzLuhVvCyRC7uOpyJ5og.BVNN.Tywa6
eeJiYy64z5IBFsKhp0NPG", "FirstName" : "Daniel", "LastName" : "Harman",
"Gender"
: 0, "DoB" : ISODate("1900-02-19T00:00:00Z"), "CreatedOn" :
ISODate("2011-07-02T
17:33:43.828Z"), "Roles" : null, "InvitedBy" : null }

from the following POCO:

public class Account
{
public ObjectId Id { get; set; }
public AccountStatus Status { get; set; }
public string Email { get; set; }
public string HashedPassword { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Gender Gender { get; set; }
[BsonDateTimeOptions(DateOnly = true)]
public DateTime DoB { get; set; }
public DateTime CreatedOn { get; set; }
public List<string> Roles { get; set; }
public List<ObjectId> InvitedBy { get; set; }
}

I'm on mongo 1.8.1 and driver 1.0.0.4098.

It seems to me the problem is that the array has been serialised as
empty rather than null, but would think the driver should be able to
cope?

Any ideas greatly appreciated.

Thanks,

Dan

Daniel Harman

unread,
Jul 2, 2011, 4:00:41 PM7/2/11
to mongodb-user
I've just checked whether this works if I initialise the array in a
constructor on the POCO. When I do, it serialises as an empty array
and the addtoset then works.

So I guess this is by design.

Robert Stam

unread,
Jul 3, 2011, 7:36:07 PM7/3/11
to mongodb-user
It is the server that requires the element value to be an array (and
BSON null is not an array).

You could also use the [BsonIgnoreIfNull] attribute to prevent an
uninitialized array from being serialized as a BSON null, because
$addToSet also works if the element does not yet exist (but if it does
exist it has to be an array).

Here's a small test I wrote to verify this:

http://www.pastie.org/2160429
Reply all
Reply to author
Forward
0 new messages