Find collection of highest value for pymongo [duplicate] - mongodb

This question already has answers here:
Select Max() with "group by" in mongodb
(4 answers)
Closed 5 years ago.
With sample data in mongodb provided below,
data = [{'name':'a','value':2},
{'name':'a','value':3},
{'name':'b','value':1},
{'name':'b','value':3},
{'name':'c','value':2}]
I already know how to find one that matches the name 'a':
db.lol.find_one({'name': 'a']},sort=[("value", pymongo.DESCENDING)])
How can I get all the data for every name with the highest value, something like this, using pymongo:
data = [{'name':'a','value':3},
{'name':'b','value':3},
{'name':'c','value':2}]

db.lol.find_one({},sort=[("value", pymongo.DESCENDING)])

You can use simple $group with $max aggregation here:
db.lol.aggregate([
{
$group : {
_id : { name : '$name' },
value : { $max : '$value' }
}
},
{
$project : {
_id : 0,
value : 1,
name : "$_id.name"
}
}
]);

Related

How to remove only rows which has null values in mongodb in a single query [duplicate]

This question already has answers here:
$unset on multiple fields in mongodb
(2 answers)
Closed 2 years ago.
I have a collection test with a record :
[{ number:"1524",
name:null,
cat_id:"126842"},
{number:"456",
name:null,
cat_id:null }]
How to remove the whole row having null values like this :
[{ number:"1524",
cat_id:"126842" },
{ number:"456"}]
I tried this but whole records are getting deleted rather than just the rows.
collection.deleteMany( { $or: [{cat_id : null },{ name : null }]
Need to remove multiple variables in a single query.
MongoDB version 4.0
In MongoDB, the $unset operator is used to delete a particular field.
You can try using the following commands to delete field that are empty
collection.updateMany({name: null}, { $unset : { name : 1 }})
This command will delete the name field from all documents where name is null. You can do a similar command for cat_id as well.
Edit : As per an answer received by me in another question I asked, You can also do the same in a single command using the following way -
collection.updateMany({
$or : [{
name : null
}, {
cat_id : null
}]
}, [{
$set: {
name : { $ifNull : ["$hobby", "$$REMOVE"] },
cat_id : { $ifNull : ["$Roll_no", "$$REMOVE"] }
}
}]
);
However, this can only be done in MongoDb V4.2 and above. You can also look at this for another way of doing it.
Hope it helps !

MongoDB - matching an array of string elements to single string element in a document [duplicate]

This question already has answers here:
Find document with array that contains a specific value
(13 answers)
Closed 3 years ago.
I'm using MongoDB v3.6.5
I have a collection called "dealers" that hold documents which look like following examples below.
{
_id: 1
country: "France"
}
{
_id: 2
country: "Belgium"
}
I have an array of country values such as;
["France","Germany","Belgium"]
I want to retrieve all documents from dealers collection where it matches values between "country" property and array values.
Use the $in operator.
db.dealers.find( { "country" : { $in : [ "France", "Belgium" ] } } )

Mongo Query in Nested Json Array [duplicate]

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 4 years ago.
A document in my collection looks like below:
{
"_id":"<uuid>",
"tests":[
{
"min":5,
"max":20
},
{
"min":15,
"max":35
}
]
}
Now, I want to find all the tests in which min >= 5.
db.coll.aggregate([
{ $match: { 'tests.min': {$gte : 5}} },
{ '$unwind': "$tests" }
]);
the above query somehow doesnt return the correct results.
You do not need to write a aggregate query for this. Use the $elemMatch operator for this. Your query will look like as shown
db.coll.find({
tests: {
$elemMatch: {
min: {
$gte: 5
}
}
}
})
The above query will return the desired result.
For more details visit
$elemMatch (query)

Save length of array in extra MongoDB field [duplicate]

This question already has answers here:
MongoDB: count the number of items in an array
(3 answers)
Closed 5 years ago.
According to this answer, I am trying to find out the size of an array and save it in the extra field.
I have a collection user_details and the document structure is something like :
{
user_id : 1,
likes : [1,2,3,4],
likes_count : 0
}
The query I'm using is as follows :
db.user_details.update({user_id : 1},{$set:{ likes_count : this.likes.length }})
BUT, it throws error that
"message" : "Cannot read property 'length' of undefined"
How do I save the length of an array in extra field?
PS: I'm using MongoDB 3.4
With MongoDB 3.4 and newer, you can use the $addFields pipeline to add the desired field ($addFields stage is equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields) and then write the result of the aggregate operation to the same collection using $out operator, thereby effectively updating the underlying collection.
If the collection specified by the $out operation already exists, then upon completion of the aggregation, the $out stage atomically replaces the existing collection with the new results collection.
To get the count, use the $size operator which returns the length of an array field. Bear in mind that all documents must have the likes field.
Overall, you need to run the following pipeline to achieve the desired update operation:
db.user_details.aggregate([
{ "$addFields": { "likes_count": { "$size": "$likes" } } },
{ "$out": "user_details" }
])
https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size
db.users.aggregate(
[
{
$project: {
likes_count: { $size: "$test" }
}
}
]
)
store the returned likes_count in an variable and perform update by providing the likes_count variable
something like this
Model.aggregate(
[
{
$project: {
likes_count: { $size: "$test" }
}
}
], (err, re) => {
console.log(err, re);
var likes_count = re[0].likes_count;
Model.update({email: 1}, {$set: {likes_count: likes_count}}, (err, d) => {
console.log(err, d);
})
}
)

Meteor - Mongo aggregate does not have $count stage [duplicate]

This question already has answers here:
MongoDB SELECT COUNT GROUP BY
(9 answers)
Closed 6 years ago.
I am using meteorhacks:aggregate package to do Mongo aggregation in Meteor. I want to get the count at the last stage of the pipeline so I use this code:
Message.aggregate([
{
$match: {
// ...
}
}, {
$count: 'count'
}
]);
It is pretty simple and should work, but I only get this error:
Exception while invoking method 'methodname'
MongoError: Unrecognized pipeline stage name: '$count'
...
Please help, thanks.
Updated: this question is not duplicated as an editor suggested, my main intention is to find out why I can not use $count
$count is available in mongodb version 3.4. For previous versions,
you will need to use $group over a constant field.
Message.aggregate([
{
$match: {
// ...
}
}, {
$group: {
_id : null,
count : {$sum : 1}
}
}
]);