Answer the question
In order to leave comments, you need to log in
How to search by sum of fields in mongodb?
The user enters the total area, then a search is performed by matching the total area. But here's the problem, there is no total area in the collection, there are several different areas, and they need to be summed up. How can I write down what I got?
query = {
$lte: {
{$sum: ["$area", "$businessArea", "$sgArea", "$forestArea"]} : maxArea
},
$gte: {
{$sum: ["$area", "$businessArea", "$sgArea", "$forestArea"]} : minArea
}
};
Answer the question
In order to leave comments, you need to log in
db.test.drop();
db.test.insert([
{_id: 1, "area": 1, "brea": 2},
{_id: 2, "area": 3, "brea": 4}]);
db.test.aggregate([
{$project: {"a": ["$area", "$brea"]}},
{$unwind: "$a"},
{$group: {_id: "$_id", "a": {$sum: "$a"}}},
{$match: {"a": {$gt: 5, $lt: 10}}}
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question