GORM get/find resource by ID using MongoDB in Grails
When a domain object is persisted in MongoDB, it is stored as a document with an ObjectId as a unique 12 bytes BSON primary key. For example, if you have a domain object Product
like
import org.bson.types.ObjectIdclass Product { ObjectId id String name static mapWith = "mongo"}
then the persisted entity in MongoDB would look like below if you save with a name as "TestProduct".
//db.product.find() in mongodb{ "_id" : ObjectId("51bd047c892c8bf0b3a58b21"), "name" : "TestProduct", "version" : 0 }
The _id
becomes your primary key for that document. To get
this document you need the primary key ObjectId. Speaking from a RESTful context, you atleast need the 12 bytes hexcode 51bd047c892c8bf0b3a58b21
as part of the request.
So in the above case, you can fetch that particular document by doing something like
Product.get(new ObjectId("51bd047c892c8bf0b3a58b21"))Product.findById(new ObjectId("51bd047c892c8bf0b3a58b21"))
Have a look at the API for ObjectId which would make clear how to retrieve a document.
When you retrieve the document as JSON, then it just shows the ObjectId class with its elements.
{ "class": "com.example.Product", "id": { "class": "org.bson.types.ObjectId", "inc": -1280996575, "machine": -1993569296, "new": false, "time": 1371341948000, "timeSecond": 1371341948 }, "name": "TestProduct"}
For completeness, here's the domain with a controller to get a resource by ID string (instead of ObjectID).
Example:Metric.get("51bf8ccc30040460f5a05579")
Domain
import org.bson.types.ObjectIdclass Metric { ObjectId id String title static mapWith = "mongo" def out() { return [ id: id as String, //convert Mongo ObjectId to 12-byte hex BSON title: title ] } }
The out()
method is used to render the resource showing its ID string (not its ObjectID).
Controller
import grails.converters.JSONclass MetricController { def index() { def resource = Metric.read(params.id) render resource.out() as JSON } }
Example JSON response for /rest/metric/51bf8ccc30040460f5a05579
{ "id": "51bf8ccc30040460f5a05579", "title": "Accounts" }