Question

How do you insert objects to a collection in using MongoKit in Python?

I understand you can specify the 'collection' field in a model and that you can create models in the db like

user = db.Users()

Then save the object like

user.save()

However I can't seem to find any mention of an insert function. If I create a User object and now want to insert it into a specific collection, say "online_users", what do I do?

Was it helpful?

Solution

After completely guessing it appears I can successfully just call

db.online_users.insert(user)

OTHER TIPS

You create a new Document called OnlineUser with the __collection__ field set to online_users, and then you have to related User and OnlineUsers with either ObjectID or DBRef. MongoKit supports both through -

  • pymongo.objectid.ObjectId
  • bson.dbref.DBRef

You can also use list of any other field type as a field.

I suppose your user object is a dict like

user = {
    "one": "balabala",
    "two": "lalala",
    "more": "I am happy always!"
}

And here is my solution, not nice but work :)

online_users = db.Online_users()  # connecting your collection

for item in user:
    if item == "item you don't want":
        continue  # skip any item you don't want
    online_users[item] = user[item]

online_users.save()
db.close()  # close the db connection
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top