Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Created November 18, 2009 05:18
Show Gist options
  • Save jnunemaker/237581 to your computer and use it in GitHub Desktop.
Save jnunemaker/237581 to your computer and use it in GitHub Desktop.
push unique in mongodb
require 'pp'
require 'rubygems'
require 'mongo_mapper'
MongoMapper.database = 'testing'
class Site
include MongoMapper::Document
key :domain, String
key :authorizations, Array
# only pushes user id if not already in array
def add_user(user)
collection.update({
:_id => _id,
:authorizations => {'$ne' => user._id}
}, '$push' => {'authorizations' => user._id})
end
end
class User
include MongoMapper::Document
key :name, String
end
User.collection.remove
Site.collection.remove
steve = User.create(:name => 'Steve')
john = User.create(:name => 'John')
ol = Site.create(:domain => 'orderedlist.com', :authorizations => [steve._id, john._id])
bh = Site.create(:domain => 'bethelhoops.com', :authorizations => [steve._id])
rt = Site.create(:domain => 'railstips.org', :authorizations => [john._id])
jn = Site.create(:domain => 'johnnunemaker.com', :authorizations => [john._id])
rt.add_user(steve)
rt.add_user(steve)
rt.add_user(steve)
pp Site.find(rt._id) # only has two user ids even though steve added multiple times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment