W
W
Wasya UK2017-06-18 17:41:33
MongoDB
Wasya UK, 2017-06-18 17:41:33

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

2 answer(s)
L
longclaps, 2017-06-19
@dmc1989

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}}}
]);

L
lega, 2017-06-19
@lega

Keep the total area in the document - simpler and works orders of magnitude faster on large collections.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question