Mogodb aggregate $ sort by field value closest to some value

I want to sort the following generalized result using the aggregation $ value of the sort price closest to 92 The aggregation I used before

db.units.aggregate([
{$match: {category: 'a'}},
{$limit: 3},
{$project: {price:1, name: 1, category: 1}}
]);

Output

[{'_id': '111', 'price': 100, 'name': 'abc', 'category': 'a'}
{'_id': '222', 'price': 90, 'name': 'efg', 'category': 'a'}
{'_id': '333', 'price': 80, 'name': 'xyz', 'category': 'a'}]

Output Required:

[{'_id': '222', 'price': 90, 'name': 'efg', 'category': 'a'}
{'_id': '111', 'price': 100, 'name': 'abc', 'category': 'a'}
{'_id': '333', 'price': 80, 'name': 'xyz', 'category': 'a'}]

Note. Price field is an embedded object.

+4
source share
2 answers

This is an interesting question. Well, thatโ€™s how I would do it.

db.units.aggregate([

{$match: {category: 'a'}},

{$project: {diff: {$abs: {$subtract: [92, '$price']}}, doc: '$$ROOT'}},

{$project :{"diff" : 0}},

{$sort: {diff: 1}}

])

Now, what happens here, I take the absolute difference in the values pricewith the specified / specified value. and so you can sort by this difference. And yes .. You can even exclude this property from the document using{$project :{"diff" : 0}}

+1
source

92 - '$price' :

db.collection.aggregate([{
    "$project": {
        "price": "$price",
        "name": "$name",
        "category": "$category",
        "diff": {
            "$abs": {
                "$subtract": ["$price", 92]
            }
        }
    }
}, {
    "$sort": {
        "diff": 1
    }
}])

:

[
  {
    "_id": "222",
    "category": "a",
    "diff": 2,
    "name": "efg",
    "price": 90
  },
  {
    "_id": "111",
    "category": "a",
    "diff": 8,
    "name": "abc",
    "price": 100
  },
  {
    "_id": "333",
    "category": "a",
    "diff": 12,
    "name": "xyz",
    "price": 80
  }
]

: mongoplayground.net/p/vfAwWMPCDbl

0

Source: https://habr.com/ru/post/1695864/


All Articles