Upsert, addToSet, renameCollection, $push and embed objects

Posted under » MongoDB on 25 Jan 2024

From basic mongodb commands.

To drop the anoneh database, use the database and drop anoneh

anodb » db.dropDatabase()

To drop collections and fields in anoneh

anodb » db.users.drop()
anodb » db.users.updateMany({},{$unset:{username:""}})

We can insert JSON like object in a field.

stud > db.mth.updateOne({name: 'hanafi'},{$set:{'que':{log:69, qid: 1}}})
stud > db.mth.updateOne({name: 'hanafi'},{$set:{'que':[{log:69, qid:1},{log:70, qid:2}]}} )

Notice that you don't have to put the brackets unless you have to put several keys.

$push is like an update and append. It will create duplicates.

The later is an object but encapsulated in an array. Great for time series or log kind of data. you append the new data at the bottom much like a log. The dictionary will be inserted as pieces of list so it allows duplicates and you have to be careful.

stud > db.mth.updateOne({name: 'hanafi'},{$push:{'que':{log:70, qid: 3}}} )

'Upsert' is a feature where you can both Update and Insert at the same time. This is how Mongodb implement upsert

stud > db.mth.updateOne({name:"hanafi"}, {$set: {'que':{log:69, qid: 1}}},{upsert:true})

For PyMongo,

myquery = { 'cid': cat }
newvalues = { "$set": {'cid': cat, 'username': str(dog.username),},}
mydb.psy.update_one(myquery, newvalues, upsert=True)

addToSet is another useful feature to prevent overwritting an array that already exists. Executing this will not create a duplicate of log:69 as long as the arrays are exactly the same.

stud > db.mth.updateOne({name:"hanafi"}, {$addToSet: {'que':{log:69, qid: 1}}})

To rename collections

stud > db.software.renameCollection("os")

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data