Reputation: 10395
When I run an upsert query, I'd like newly generated documents to have an _id
of type string instead of a Mongo Id. It it possible to do that? Currently I'm doing
var data = { test: 1234 };
edgesCollection.update(data, { $set: data }, { upsert: true });
But this creates a document like
{ _id: { [String: '583e1ecd39ff3ba3228523ce'] _str: '583e1ecd39ff3ba3228523ce' },
test: 1234 }
While I'd like to get
{ _id: '583e1ecd39ff3ba3228523ce', test: 1234 }
Upvotes: 0
Views: 1978
Reputation: 14456
You can use the $setOnInsert
operator within the update, for example:
var data = { test: 1234 };
db.edgesCollection.update(data, { $set: data, $setOnInsert: {_id : "my string id"} }, { upsert: true });
> db.edgesCollection.find()
{ "_id" : "my string id", "test" : 1234 }
See https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/ for more details.
Upvotes: 3
Reputation: 1200
You can specify the _id field. If you don't specify it will be auto generated. For this to work you have to use insert instead of update (check it out :-) I really advise you to leave the _id as a ObjectId.
Upvotes: 0