How to get the value of a document in mongodb atlas function

I have a collection order and in order collection I am having a document order Items

           {
                "_id": "6466279bec6576a00b527434",
                "brand": "SS",
                "product_name": "Gunther ",
                "gst": 0
            }

I using findOne in mongodb atlas function and then trying to access the brand name but unable to parse and get the brand value, I have tried EJSON.parse(item).

What I am trying to achieve is

var product = productColl.findOne({"_id": new BSON.ObjectId("6466279bec6576a00b527434") })
        const product_item = EJSON.parse(product);
        
        var orderObj
        orderObj = order_items.map((item, idx) => {
          return {
            ...item,
            brand:  product_item.brand,
            product_name: product_item.product_name
          }
})

Hey @Zubair_Rajput,

Thanks for reaching out to the MongoDB Community forums :sparkles:

Based on the sample documents you shared, I’ve written a JavaScript code snippet that retrieves the brand name when executed in a MongoDB Atlas function. Sharing the code snippet for your reference:

exports = async function(arg){
  // Find the name of the MongoDB service you want to use (see "Linked Data Sources" tab)
  var serviceName = "mongodb-atlas";

  // Update these to reflect your db/collection
  var dbName = "db_name";
  var collName = "collection_name";

  // Get a collection from the context
  var productColl = context.services.get(serviceName).db(dbName).collection(collName);

  var product = await productColl.findOne({ "_id": "6466279bec6576a00b527434" });
  const product_item = JSON.parse(EJSON.stringify(product));
  
  if (product_item) {
    const brand = product_item.brand;
    return brand;
  }
  return null; // Return null if the product_item is not found
}

It will return the following output:

> result: 
"SS"
> result (JavaScript): 
EJSON.parse('"SS"')

Please let us know if you have any further questions.

Best regards,
Kushagra

1 Like

Thanks for the fast reply, yea I am getting result.
But one more query I am getting mrp like this

"mrp": {
   "$numberInt": "160000"
 },

Now I want to access 16000 and do some calculation.
Thanks again bro

Hello @Zubair_Rajput,

I noticed you asked a similar question on another thread. If the answer in that thread solved your issue, I will close this thread. If not, let’s continue the discussion in that thread to keep all the information in one place.

Best,
Kushagra