Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi document insert using mongoengine into mongodb

Tags:

In my flask app I am using MongoeEgine. I am trying to insert multiple documents into my places collection in my MongoDB.

My document class is defined as

class places(db.Document):    name = db.StringField(max_length=200, required=True)       loc = db.GeoPointField(required=True)    def __unicode__(self):     return self.name      a=[]     a.append({"name" : 'test' , "loc":[-87,101]})     a.append({"name" : 'test' , "loc":[-88,101]})     x= places(a) 

The last statement fails

x= places(a) TypeError: __init__() takes exactly 1 argument (2 given) 

I also tried to save this to my instance

places.insert(x) places.save(x) 

both fail. Please help.

like image 324
user1340513 Avatar asked Feb 28 '13 18:02

user1340513


People also ask

How do I add an array of documents in MongoDB?

db.collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method. The following example inserts three new documents into the inventory collection. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.


1 Answers

Places.objects.insert doesn't take a list of dictionaries it has to be Places instances. Normal operations would be to create individual instances of Places and save or insert eg:

Places(name="test", loc=[-87, 101]).save() Places(name="test 2", loc=[-87, 101]).save() 

However if you want to do a bulk insert you can pass a list of Places instances and call insert on the objects queryset eg:

Places.objects.insert([Places(name="test", loc=[-87, 101]),                         Places(name="test 2", loc=[-87, 101])]) 
like image 101
Ross Avatar answered Oct 21 '22 15:10

Ross