0

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?

Mike
  • 709
  • 7
  • 19

3 Answers3

0

After completely guessing it appears I can successfully just call

db.online_users.insert(user)
Mike
  • 709
  • 7
  • 19
0

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.

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
0

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
ferstar
  • 11
  • 1
  • 1
  • 4