Home > OS >  select single document with minimum value $Min mongodb
select single document with minimum value $Min mongodb

Time:04-27

I have made several efforts to select a single specific document that contains the minimum value from the database.

       let Lowestdate = await BTCMongo.aggregate(
        [ 

          // { "$sort": { "name": 1, 
          {
            $match : { "createdAt"  : { $gte: new Date(last),$lte: new Date(NEW) } } },
          
             {

            $group:
            {
              _id:null,
              minFee_doc:{$min: "$$ROOT"},
              minFee: { $min:{$toDouble:"$one"}},
              firstFee: { $first: "$one" },
              lastFee: { $last: "$one" },
              maxFee: { $max: {$toDouble:"$one"}},
              
            }
          },
        ]
       ).then(result => {}):

with minFee_doc:{$min: "$$ROOT"}, I have been trying to return the document containing the minimum $min but it keeps returning document containing $first

How do i select the document with minimum value?

Note : i will like to return the whole document including the "CreatedAt" "UpdatedAt", and _id. of the document containing the minimum value

Expected Result should look like:

{
        "minFee_doc": {
            "_id": "61e84c9f622642463640e05c",
            "createdAt": "2022-01-19T17:38:39.034Z",
            "updatedAt": "2022-04-24T14:48:38.100Z",
            "__v": 0,
            "one": 2
        },
        "minFee": 2,
        "firstFee": 3,
        "lastFee": 5,
        "maxFee": 6
    }

Edit: also to provide a single document not multiple

CodePudding user response:

$push all docs in $group then $set the array with $filter

db.collection.aggregate([
  {
    $match: {}
  },
  {
    $group: {
      _id: null,
      minFee_doc: { $push: "$$ROOT" },
      minFee: { $min: { $toDouble: "$one" } },
      firstFee: { $first: "$one" },
      lastFee: { $last: "$one" },
      maxFee: { $max: { $toDouble: "$one" } }
    }
  },
  {
    $set: {
      minFee_doc: {
        $filter: {
          input: "$minFee_doc",
          as: "m",
          cond: { "$eq": [ "$$m.one", "$minFee" ] }
        }
      }
    }
  }
])

mongoplayground

  • Related