reach4thelasers
reach4thelasers

Reputation: 26909

MongoDB / C# API - How to determine if a nested document exists

A Newsfeed Post has a number of 'likes'

"Likes" : [

{
    userid: ObjectId(ae12bcd323421223),
    username: "user1",
    likedate: ISODATE(xxx)
},

{
    userid: ObjectId(ae12bcd323421224),
    username: "user2",
    likedate: ISODATE(xxx)
}


]

A Person can only like a post once, therefore userid/username need to be unique.

I've tried AddToSetWrapped - but it fails obviously because the DateTime is different and it adds the object anyway. I currently have no unique indexes on the array but can change that if necessary?

How do I check for the existence of a particular userid in the Likes array and only add it if the userid does not already exist? (either as one atomic operation, or as two operations)?

Upvotes: 0

Views: 641

Answers (1)

mnemosyn
mnemosyn

Reputation: 46311

A Person can only like a post once, therefore userid/username need to be unique. [...] I currently have no unique indexes on the array but can change that if necessary?

Note that unique keys don't cover that scenario. A document in MongoDB can never violate itself through a unique constraint.

However, Update.AddToSetWrapped is the correct method. You could use findAndModify like so:

_db.FindAndModify<Post>(
   Query.And(
       Query.EQ("_id", post.Id), 
       Query.NE("Likes.userId", requestingUserId)), 
   Update.AddToSetWrapped("Likes", newLike));

This way, it will not find the post if there already is a 'like' for the given user id, and hence, won't call the update.

Upvotes: 1

Related Questions