Update field and value mongoDB - database

Let say I have a collection. I want to change the field name and value in the whole collection like this
Current:
language:"en",
documentId:"123"
Desired:
languages:["en"],
documentIds:["123"]
db.foo.... Thank you in advance

Query
empty filter {} and updateMany to update all collection
you can use "$field" to refer to filed and and array literals
and $unset to remove the old fields
*pipeline update requires MongodDB >= 4.2
Test code here
updateMany({},
[{"$set": {"languages": ["$language"], "documentIds": ["$documentId"]}},
{"$unset": ["language", "documentId"]}])

Related

Find dict in array without knowing the index mongodb

I have a MongoDB document with an array called forms, inside the array each item is a dictionary, there are a couple of documents in this format, each document has an email field for user identification, and each dictionary has an identifier called title.
My question is how do I check if a specific dictionary is inside the array using the title parameter and retrieve the index, and how do I ensure that I will find the item in the current user document?
Thanks
Ok after some research I found a way:
def already_exists(self, new_form, email):
raw_idx = list(self.users_data_collection.aggregate(
[
{'$match': {'email': email}},
{'$project': {
'index': {'$indexOfArray':['$forms.title',new_form['title']]}
}
}
]
)
)
return raw_idx[0]['index']
I filtered it with the email param to find the correct document and the raw_idx return list of dict which contains the _id field and index field, and then i\I returned the index only.
I hope I have helped someone in need.

MongoDB: deleting an array value in multiple documents in one collection using pymongo

Afternoon all. I hope you can help with a problem. I am using creating a Flask app and using pymongo and I need to delete a singular array value from multiple arrays across many documents within one collection. I have recipe documents within a 'recipes' collection, and within each of them is an array ('category') that can be between 1 and 3 values in length. I have a feature available within the admin section of my site that allows for the deletion of a category from the 'categories' collection and so, to go with that, I want to delete any instances of that category value within the 'category' array on any recipe document within the recipes 'collection'.
I have managed to do this on a single document:
mongo.db.recipes.update(
{"_id": ObjectId("60df2eec9df14e58d0c698c8")},
{"$pull": {"category": category_id}}
)
but have not managed this on the collection as a whole I have determined I need to use the $all with the $pull operator on the collection using the 'update_many' query and have so far tried:
mongo.db.recipes.update_many({"category": {"$all": {"$pull": {"category": category_id}}}})
mongo.db.recipes.update_many({"$all": {"$pull": {"category": category_id}}})
mongo.db.recipes.update_many({"category": {"$pullAll": {"category": category_id}}})
None of them work. I keep getting a the error:
TypeError: update_many() missing 1 required positional argument: 'update'
Any help would be appreciated.
Read - https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html?highlight=update_many#pymongo.collection.Collection.update_many
1st parameter is filter which will be {} if you want to update all document
mongo.db.recipes.update_many(
{} // filter filter,
{} // update
)
mongo.db.recipes.update_many({ }, {"$pull": {"category": category_id}})

mongoose $literal in find method projection

I have a mongoose find method like this,
photo.find({},{
name:1,
src:1,
likes:{$literal:[]},
dislikes:{$literal:[]},
}).then(photos => ....)
what I want is, when I run the code likes and dislikes field must be an empty array for every record.
I try this way but not working.
Unsupported projection option: likes: { $literal: 1 }
Any idea to add default value for any field in find method ?
As per mongoose, document schema is constructed during its creation. So you can also edit the schema with a default value, so for every record, when it is created it will create likes, and dislikes with empty values.
You can also do this way, if you feel the schema control is not in your hands.
https://mongoosejs.com/docs/2.7.x/docs/defaults.html
photo.find({ 'name' : '1', 'likes': {$ne: []}})

MongoDb replaceOne() but wanted few field

in case of replaceOne() --> it replace whole object by new object -->what if i want few field of old object as it and replace that object by new object
replaceOne will replace the whole document and update with the one you are replacing you need to use updateOne instead this will only update specific fields which you wanted rest fields will be as it is
For example
db.restaurant.updateOne(
{ "name" : "Central Perk Cafe" },
{ $set: { "violations" : 3 }},
{upsert:true}
);
here upsert:true option will help in inserting new documents if it doesn't exist you can read more about it here https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/
you can use update
if you document is {name:"company",country:"India",owner:"me"}
db.company.update({
_id:*id*
},
{$set:{
name:"mycompany",
country:"United Kingdom"}})

Firebase: query by array field itself(not by an item of the array)

in my 'rooms' collections, each document has the fields like the following,
{
"createdAt" : 2020.6.4 12:00,
"titleArray" : ["icecream", "summer"]
}
And I want to query to check if a collection contains a document with ["icecream", "summer"] as "titleArray" field, I couldn't find a way to query by an array field itself. In other words, is there a way to passing in an array directly?

Resources