Search code examples
mongodbreactivemongoplay-reactivemongo

How to remove _id from MongoDB results?


I am inserting json file into Mongodb(with Scala/Play framework) and the same getting/downloading it into my view page for some other requirement, but this time it is coming with one "_id" parameter in the json file.

But I need only my actual json file only that is not having any any "_id" parameter. I have read the Mongodb tutorial, that by default storing it with one _id for any collection document.

Please let me know that how can I get or is there any chance to get my actual json file without any _id in MongoDB.

this is the json result which is storing in database(I don't need that "_id" parameter)

{
        "testjson": [{
        "key01": "value1",
        "key02": "value02",
        "key03": "value03"
    }],
  "_id": 1
 }

Solution

  • If you have a look at ReactiveMongo dev guide and to its API, you can see it support projection in a similar way as the MongoDB shell.

    Then you can understand that you can do

    collection.find(selector = BSONDocument(), projection = BSONDocument("_id" -> 0))
    

    Or, as you are using JSON serialization:

    collection.find(selector = Json.obj(), projection = Json.obj("_id" -> 0))