I used InsertOne() for bulk insert.
user1 = InsertOne({"user_id": 1})
user2 = InsertOne({"user_id": 2})
collection.bulk_write([user1, user2])
If user_id = 1 already exist in collection, it throw batch op errors occurred errors.
I wonder that is there any method for only insert if data doesn't exist?
(Can't using get data and compare if data exist because I'm using bulk_write)
What you can do is : Use ReplaceOne with upsert:true. So that if the document already exists update wont have any effect, and if it doesn't exist, it will create the new document.
Try this:
user1 = ReplaceOne({"user_id": 1},{"user_id": 1},upsert = True)
user2 = ReplaceOne({"user_id": 2},{"user_id": 2},upsert = True)
collection.bulk_write([user1, user2])
Make sure you pass all the data you need to store in the User document, in the second argument of ReplaceOne
Related
When I use mongo-ruby-driver and I insert new document it returns generated '_id':
db = MongoClient.new('127.0.0.1', '27017').db('ruby-mongo-examples')
id = db['test'].insert({name: 'example'})
# BSON::ObjectId('54f88b01ab8bae12b2000001')
I'm trying to get the '_id' of a document after doing an insertion using Moped:
db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')
id = db['coll'].insert({name: 'example'})
# {"connectionId"=>15, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
How I get the id using Moped?
Update:
I also try use safe mode but it doesn't work:
db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')
db.with(safe: true) do |safe|
id = safe['coll'].insert({name: 'example'})
# {"connectionId"=>5, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
end
After inserting/saving, the returned object will have a property inserted_id which is a BSON::ObjectId:
# I'm using insert_one
result = safe['coll'].insert_one({name: 'example'})
result.methods.sort # see list of methods/properties
result.inserted_id
result.inserted_id.to_s # convert to string
From this issue:
It would be nice, but unfortunately Mongo doesn't give us anything
back when inserting (since it's fire and forget), and when in safe
mode it still doesn't give the id back if it generated it on the
server. So there really isn't any possible way for us to do this
unless it was a core feature in MongoDB.
Your best bet would be to generate the id before inserting the document:
document = { _id: Moped::BSON::ObjectId.new, name: "example" }
id = document[:_id]
can you please help me,
I am trying to copy all collections in a particular database into create new database and move that collection into it.But the following code does not work. and my colleciton name in the db contains two part ' mg2.data' ,'mg32.data' i want to create new database mg2 and copy collection name as data.
collection name mg2.data suppose to be in mg2 database and collection name data.
db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
//print(dbName)
db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
}
});
Here is my situation details.
I am having Db name Master and it contains about 60-70 collections its names like(mg1.data,mg2.data,mg3.data)
and i want it to be like
db name mg1 and collection name data
db name mg2 and collection name data and so on..
i am facing the problem that when in the first design write operation locks entire database(Master). i cannot go for sharding and all now.
I got this approach working for me.I dont know is this best aproach
db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
print(dbName+'\n');
//db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
db[a].find().forEach(function(d){ db.getSiblingDB(dbName)[col].insert(d); });
}
});
I want to access a document in collection by 'name' attribute for getting its ObjectId so that i can insert that unique objectid to other document for reference.
cursorObject = db.collectionIngredient.find({'name': 'sugar'})
I want _id field of cursorObject.
cursorObject.'_id' or cursorObject._id not working.
I have tried __getitem__, __getattribute__ and so much internet surfing but couldn't able to find a way.
Please help
First, as #jjmartinez pointed out, find returns a cursor, which you need to iterate over, in order to get hold of the documents returned by your query. The _id field belongs to the documents, not the cursor.
I'm guessing that in your case the name is unique, so you can avoid cursor/iterating if you use find_one instead of find. Then you get the document directly.
Then, to access the _id, you just need a standard dict-item access:
id = doc['_id']
So we get:
ingredient = db.collectionIngredient.find_one({'name': 'sugar'})
if ingredient is not None:
id = ingredient['_id']
else:
id = None
When you do cursorObject = db.collectionIngredient.find({'name': 'sugar'}) you have a collection of documents, not a single element. So you need to explore all the collection. You need to iterate inside the cursor:
try:
cursorObject = db.collectionIngredient.find({'name': 'sugar'})
except:
print "Unexpected error:", sys.exc_info()[0]
for doc in cursorObject:
print doc
Here you have the Pymongo Tutorial
I need to duplicate (clone) an object in the collection via dbshell. Having something like this :
> db.users.distinct( 'nickname' )
[
"user1",
"user2",
"user3",
"user4"
]
>
where user1 select a complex object in users collection, how can I duplicate the object then change (rename) user1 field in userX ?
Code
> user = db.users.findOne({'nickname': 'user1'})
> user.nickname = 'userX'
> delete user['_id']
> db.users.insert(user)
Description
You need to find user object and put it into the variable. Than you need to modify the property you want and than you need to insert the whole object as new one. To achieve that you need to delete _id property that the object already has. And than just use insert to create the new one.
Do not delete the _id property; for some reason some values lose their type. For example, integers are converted to doubles.
Use this solution:
var user = db.users.findOne(...)
user._id = new ObjectId()
// set other properties
db.users.insert(user)
The _id field is a required field and we can't delete it like that. What I do is call toJSON() to the returned object and then delete the _id.
var rObject = dbObject.toJSON();
delete rObject._id;
db.insert(rObject);
I have a simple example:
conn = Connection()
db = conn.livestat
coll = db.cmn1
coll.insert({'test': 1 });
before insert collection autocreate. How to disable this function or add param to autocreate (for example I want to create a capped collection ) ?
You'll have to do it manually. See the doc.
db.createCollection("cmn1", {capped:true, size:100000})
You must create the capped collection before you write to it for the first time. Please use this function:
http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.create_collection