I have a fairly straight forward database structure I would like to create with MongoDB. My structure looks like this:
{url: value,
users: {user_id: value}}
An example document might looks like this:
{'url': 'http://stackoverflow.com/', users: {'billy': 12, 'tommy': 2}}
I’m using PyMongo to update my database and add documents as show above. I can successfully add data to my database, but I cannot seem to duplicate the above data structure.
for d in data:
foo.update(
{'id': d.get('url')},
{'$addToSet' :{'users': {d.get('user'): 'NaN'}}},
upsert=True)
The above code inserts but the ‘user’ structure is not what I intended. I would like:
users: {'billy': 'NaN', 'tommy': 'NaN'}
and I get:
users : [ { 'billy' : "NaN" }, { 'tommy' : "NaN" } ]
Can anyone help? Thanks for your time.
Per my comment above I would suggest not embedding a document but instead using an array. The following would work well:
This way you can leverage
$push,$pulletc. as well as$addToSet. For the latter you could add a new user like this:Now lets say you just wanted to increment a value for a given user, you could easily do that too:
To see more things that you could do with the schema I proposed I would read this