Add a new unique ObjectId to each document in collection - mongodb

I have an existing collection users where the _id field is a string instead of an ObjectId.
Is there a query that can update all documents in the collection and add a unique ObjectId for each document to using a new field called UID?

You can generate a new ObjectId using new ObjectId() in the shell.
db.users.find().forEach(function(doc){
doc.UID = new ObjectId();
db.users.save(doc);
})

Related

Firestore: Save document ID into the Field

I'm using Swift here and confused about how to save the document ID into itself field. Here is an example :
I have a collection named "menu"
here we can focus on the one and only document in the "menu" collection which saved the name field "ayam goreng". How do i save the document ID "
7D3fuw3fri6oj287SySW" to the field named "menu_id" inside the document?
As shown in the documentation on adding a document:
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():
let newCityRef = db.collection("cities").document()
// later...
newCityRef.setData([
// ...
])
In your case, you can then get the document ID from the new ref with:
newCityRef.documentId

how to find item in mongo collection when _id is object?

I have mongo collection which have _id key as object of 2 key value pair. (_id = {"id":123, "slice":1}). how can I use pymongo find() to fetch an item using _id? sample collection item looks like this.
Use the uuid module as follows:
db.foo.drop()
import uuid
uu = uuid.uuid4()
uu2 = uuid.uuid4()
db.foo.insert_one({'_id':{'execution_id':uu, 'slice':1}, 'realm':'bar'})
print("should find it:", db.foo.find_one({'_id':{'execution_id':uu, 'slice':1}}))
print("should NOT find it:", db.foo.find_one({'_id':{'execution_id':uu2, 'slice':1}}))

Update entire document in mongodb using morphia

I have document which I need to update but updated parameters are not same all the time it depends on user. So how can I update document or replace whole document with new values based on id.
You wrap your updated values in a Map the set the update:
Map<String, Object> updateInfo; // Key is db column name, value is updatedValue
Then create update operations:
Query<Entity> filter = datastore.createQuery(Entity.class)
.field("_id", id);
UpdateOperations<Entity> updateOps = datastore.createUpdateOperations(Entity.class);
updateInfo.entrySet().forEach(e -> updateOps.set(e.getKey(), e.getValue());
datastore.update(filter, updateOps);
By this way, you can update entity with any number of fields

pymongo get rid of ObjectId

I'm using pymongo to insert records into my mongodb database:
mongo = MongoClient('localhost',3001)
db = mongo.meteor
db.clients.insert({"hi":"test"})
the id of the inserted record is of type:
_id: ObjectId("57e92af647700265a2427f69")
is it possible to insert a record and generate an id as a string only without the Objectid?
You can just specify the _id on insert:
db.clients.insert({"hi":"test", "_id":"123"})

Update an array using Jongo

I have a mongodb collection of the form
{
"_id":"id",
"userEmail":"userEmailFromCustomerCollection",
"customerFavs":[
"www.xyz.com",
"www.xyz.com",
"www.xyz.com"
]
}
I need to add an element to the customers favs array using Jongo , I am using the following code snippet to do so .
String query = "{userEmail:'"+emailId+"'}";
customerFavCollection.update(query).with("{$addToSet:{customerFavs:#}}", favUrl);
My problem , is that I need to upsert the document if the document does not
exist already , how can I do so using Jongo, I know an easier option would be to retrieve the document by Id and if it does not exist then insert the document using save() , but I am trying to avoid the extra retrieve.
You can add upsert() on the query.
customerFavCollection.update("userEmail:#", emailId)
.with("{$addToSet:{customerFavs:#}}", favUrl)
.upsert();