0

I am trying to get some dummy _id from mongodb, for that i have written the following snippet of code, but it is throwing BulkWriteError.

def get_unique_ids(count):
    return db.insert_many([{}] * count).inserted_ids

Exception:

execute_command
    raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred

But the following code works perfectly, I wanted to know what is the difference between the two.

def get_unique_ids(count):
    return db.insert_many([{} for i in range(count)]).inserted_ids
daemon24
  • 1,388
  • 1
  • 11
  • 23
  • You do realize the `ObjectId` values are actually generated "client side" and not on the server. So there is no need to "force" insertion on the server just to get a range of `ObjectId` values. Simply create new `ObjectId` instances in a loop. – Neil Lunn Jul 13 '17 at 08:22
  • I do use ObjectId() to get unique ids, but i don't have any document source to know the bson.ObjectId generates unique Ids, since there multiple workers which handle request in the same server i was trying to move this to mongodb. Could you please provide the source for "ObjectId values are actually generated client side"? – daemon24 Jul 13 '17 at 09:57
  • The source? The driver documentation itself. The MongoDB documentation and lots and lots of references over 8 years or so. The only time the "server" ever generates an `_id` value in "all" supported drivers is in fact as an "upsert". And then only if you did not explicitly supply the `_id` yourself within the query arguments. Just use a `.map()` and repeat values returning a new `ObjectId` instance from the `bson` package. No idea why you are doing this outside of writing something, but that is how it's done. – Neil Lunn Jul 13 '17 at 10:02
  • So I can use ObjectId() to get new ids, which will be unique even if the id are generated in multiple servers inside multiple workers at the same time? – daemon24 Jul 13 '17 at 11:29
  • Read the definition https://docs.mongodb.com/manual/reference/method/ObjectId/#description. It is not possible to receive a duplicate value. That's why we use them. Also answered in a question here already.https://stackoverflow.com/questions/4677237/possibility-of-duplicate-mongo-objectids-being-generated-in-two-different-colle – Neil Lunn Jul 13 '17 at 11:37
  • I am getting a duplicate _id error when using just ObjectId to get a new _id, this is happening very rare but somehow _id are duplicating. – daemon24 Oct 23 '17 at 20:36

0 Answers0