Tarlen
Tarlen

Reputation: 3797

check if value exists in mongo document array

I have a collection Items, in which I have an array storing the IP addresses of all the clients who have visited the item's URL

{ 
    "title" : "asdads", 
    "artist" : "adsdd", 
    "description" : "adas", 
    "category" : "sheetmusic", 
    "price" : 15, 
    "publish" : true, 
    "downloadUrl" : "https1f5c69ce0c9eb1bc5032362d853d", 
    "s3key" : "ee33e7320b8a4fe881f5c69ce0c9eb1bc5032362d853d", 
    "userId" : "LnsYqhsefu7ZmQmTq", 
    "views" : 0, 
    "downloads" : 1, 
    "likes" : 0, 
    "dislikes" : 0, 
    "createdAt" : ISODate("2015-02-21T17:17:40.491Z"), 
    "_id" : "GM8M37EWTfZ2Jwatu" 
    "IPs: [
     "0.0.0.0"
    ]
}

I want to know whether a given item document has an ip address in it's array, if not, then add it, else return true

what is the best and most performant approach?

Upvotes: 0

Views: 905

Answers (1)

Sede
Sede

Reputation: 61273

You can do this using the $addToSet operator. To check if your array already contains given value all you need is the the number of modified document which you can get using nModified

db.collection.update({_id: "GM8M37EWTfZ2Jwatu"}, 
    {$addToSet: {IPs: "98.245.153.111"}}
).nModified

Output

1

Upvotes: 2

Related Questions