How to sort documents in MongoDB based on keys inside a dictionary in document using MongoEngine Python? - python-3.x

So I have documents of this type in my MongoDB Collection:
{
"_id" : ObjectId("606c66c875a2fe6153bfc71f"),
"t_id" : "12345678a",
"r_id" : "r12345678a",
"t_e_stats" : {
"acc" : "70"
},
"register_time" : ISODate("2021-04-06T19:18:56.890Z")
}
There are multiple of these documents with same 't_id' and different 't_e_stats' dictionary. But all 't_e_stats' dictionary have 'acc' key in them. Now I want to query the entry for a particular 't_id' with the maximum value of 'acc' in the 't_e_stats' dictionary. How do I do that in MongoEngine? Or I have found there are ways to run PyMongo queries in MongoEngine also, how to use that too if possible?

As commented by OP
Model.objects(t_id="12345678a").order_by("-t_e_stats.acc").first()
if anyone is interested in not only the object but also the JSON document, then you can do this:
[data_entry._data for data_entry in Model.objects(t_id="12345678a").order_by("-t_e_stats.acc")][0]
Use .sort
https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html?highlight=find%20one#pymongo.collection.Collection.find_one
mycol.find_one({ "t_id" : "12345678a" }).sort("t_e_stats.acc", pymongo.DESCENDING)
This will return 1st record where t_e_stats.acc is max.
mongo shell
db.collection.find({ "t_id" : "12345678a" }).sort("t_e_stats.acc", -1).limit(1);
Mongoengine
Model.objects.get(t_id="12345678a").order_by("-t_e_stats.acc").first()

Related

How to query field exist some document in firebase

I using firebase, nodejs and i have a question how to query field exist some document.
Example :
Collections : users => document : A with field {
....
is_correct: true
}
document : B with field {
.....
}
In my above example , i have two document in collection users. On document A i have field is_correct: true and on document B field is_correct not exist.
My collection users about 15.000 document and it have 50 document contain field is_correct: true
When i write code look like :
await firestore.collection('users').where('is_correct', '==', true).get();
it can get correct me 50 document. But i don't understand it can using index on field is_correct or not ? And it can query best performance ? I understand firebase can't get document if field undefined. It impart in case ? Please help ? Thanks you
For a simple query like
firestore.collection('users').where('is_correct', '==', true)
you don't need to configure any index, Firestore does it automatically.
As you mentioned, only documents where the given field exists can match the query.
And this is the case also for Not-equal (!=) and not-in queries: they exclude documents where the given field does not exist, as explained in the documentation.
Also, note that a field exists when it's set to any value, including an empty string (""), null, and NaN (not a number).
So, in conclusion, if you want to query for documents where is_correct is not true, you need to create this field in these documents with a value different than true.

Mongoose not updating key value pairs stored with Object Schema

This is for rating feature in my application. I want to use the user-mail as key and the users rating as the value
Eg:
ratings : {
"user1#gmail.com" : 5,
"user2#gmail.com" : 4
}
I don't prefer using arrays since their could be just a single rating from each user.
I tried inserting a new key value pair in mongo using compass and it worked fine but when I did this using mongoose with type as Object in express, it is not working. Only the first key value pair is stored the user2's key value pair is not getting added.
Thanks in advance.
Schema type : Object
I have solved this using the method markModified("fieldname") before save().
Example:
mongooseSchema.markModified("ratings");
mongooseSchema.save();

Increment nested field value in mongodb if exists or create nested fields

I need to increment the multi level nested field value if it exists or create the complete nested field Object structure.
Structure of my document
Doc1 {
_id:ObjectId(),
myField: {
nested:{
x: 5,
y: 10,
z: 20
}
}
}
Goal Explanation: I need a way to write a single query:
If myField exists: Increment the value of my nested field
myField.nested.x by 10.
If myField does not exists: Create the below field with initial values same as given in the Doc1.
Attempt and explanation:
db.collection('collectionName').findOneAndUpdate(
{_id:"userId","myField" : { $exists : true }},
{$inc:{'myField.nested.x':10}
})
This way, I can increment the nested field if it exists but in case of non existence I cannot set myField as same as Doc1.
Although, I can use another query after response in my NodeJs callback to achieve my required behaviour. But I need some elegant solution in a single query.
I am using MongoDB version 4.0.4, Thanks in Advance.
Try this query
If the field does not exist, $inc creates the field and sets the field to the specified value.
db.collection('collectionName').findOneAndUpdate({_id:"userId"},
{$inc:{'myField.nested.x':10}
})

Update same field in different documents with different value at once with MongoDB

I didn't found a question similar to mine and i'm not sure it's possible. I have several documents, each document is a person, for example :
{
"name" = "Paul",
"score" = 105
}
{
"name" = "John",
"score" = 98
}
Before the update i have a dict (in python) with the name and the new score {"Paul": 107, "John": 92}. How do i update the score in all the documents from the dict in one request ?
You can not update multiple documents with different conditions in a single query. You can refer MongoDB update doc. MongoDB introduced a new parameter as multi but it has a different meaning. update query with param { multi: true } will update multiple documents only which will match the same condition which we set in query part.
Optionally you can update multiple documents with loop through your query. This feature is still missing in MongoDB so we are also doing such thing in the same way.

Find all collections in mongodb with specific field

There is more than 40 collections in database I am currently working on.
One of the major key in all the collections is "account".
I need to know all such collections where there is a field called "account".
Is there a query to get or a js script which prints all such collections?
In Oracle I was using :
SELECT * FROM ALL_TAB_COLUMNS WHERE COLUMN_NAME LIKE 'account';
Any inputs is helpful.
Thanks in advance.
The following mongo script will print out all collection names where at least one document contains an account field.
db.getCollectionNames().forEach(function(collname) {
var count = db[collname].find({"account": {$exists: true}}).count();
if (count > 0) {
print(collname);
}
})

Resources