Extract Decimal from Decimal128 with Mongoose - MongoDB

前端 未结 3 1054
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 13:25

I\'m querying Mongo in Nodejs with Mongoose and attempting to extract the numeric value of multiple fields stored as a Decimal128. However, the value is oddly wrapped in que

3条回答
  •  广开言路
    2021-01-19 14:02

    Method 1: .

    use toString(). It will convert the object to string.

    find((docs) => {
       let result = docs.map((doc) => {
           if(doc.open){
              doc.open = doc.open.toString();
           }
    
           if(doc.close){
              doc.close = doc.close.toString();
           }
    
           return doc;  
       });
    
        //send modified output
        res.json(result);
    })
    

    output as follows:-

    /*
    [
      {
        "open":  "86.13",
        "close": "85.64"
      },
    ]
    */
    

    Method 2: Mongodb 4.0 above,

    db.myCollection.aggregate([
      {$match:{
       //...
       //...
       }},
    
    
      { $addFields : {
            open: {"$toString" : "$open"},
            close : {"$toString" : "$close"},
        }},
    ]);
    

提交回复
热议问题