Result of findOne method without value type

This is part of my document:

"gameData": {
   "gold": 0
}

Through the findOne method, I wanted to obtain the value of “gold” in the document.

myCollection.findOne( 
   { "userData.username": username},
   { "gameData.gold":  1, "_id": 0} 
);

The result is: {"gameData":{"gold":{"$numberLong":"0"}}}

I wanted to know if it was possible to have only the value of “gold” as a result, or a normal JSON without the “$numberLong” key (I’m not sure but I think the current result is in BSON format, but I couldn’t find a function to convert it to JSON).

Thanks.

Hello Andrea,

The value of gold is in JSON format, in the output. It is the the MongoDB representation of BSON value in JSON format. See:

To get the value of gold field’s value only from the embedded document gameData, you can use one of the following ways from mongo shell:

const doc = db.test.findOne( { }, { "gameData.gold":  1, "_id": 0 }  );
printjson(doc.gameData)

Prints: { "gold" : NumberLong(12345678) }

Or, an aggregation query:

db.test.aggregate( [ 
    { 
        $project: { _id: 0, gold: "$gameData.gold" } 
    } 
] )

Hi @Prasad_Saya ,
thank you for your answer.
So there is no possibility to receive a string like { "gold" : 12345 } as return?

You can. The default numeric data type for MongoDB is a double. If you dont use any type it will be a double. So, convert the long to a double and you get the result in the desired format.

db.test.aggregate( [ 
    { 
        $project: { _id: 0, gold: { $convert: { input: "$gameData.gold", to: "double"  } } }
    } 
] )

Hii @Andrea

I assume that since we chatted about MongoDB realm this is a return of a document from a webhook in EJSON format which is what could be expected when just returning it.

However, you could set the response body with the query result parsed to JSON:

doc = await myCollection.findOne( 
   { "userData.username": username},
   { "gameData.gold":  1, "_id": 0} 
);

response.setBody(JSON.stringify(doc));

See this docs:

Let me know if I am correct. :slight_smile:

Best regards,
Pavel

1 Like

Thank you both very much for your answers!
Pavel, you understood perfectly what I needed. Thank you very much!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.