Docs Menu
Docs Home
/ / /
Mongoid
/

Documents

On this page

  • Overview
  • Work with Documents
  • Additional Information

In this guide, you can learn about the Mongoid::Document module in Mongoid. The Document module is a Ruby implementation of a MongoDB document, which stores data in field-and-value pairs. To learn more about the terminology, structure, and limitations of MongoDB documents, see Documents in the Server manual.

You must include the Mongoid::Document module in any class that you want to persist to MongoDB. By including the Document module in your model class, you can use its methods on instances of your model class.

The following code demonstrates how to include the Document module in a sample Person model class:

class Person
include Mongoid::Document
field :name, type: String
end

You can find more information about the Document module in the API documentation.

You can store instances of your models directly in a collection, or you can embed them in other classes that use the Document module. When you save a Document instance to MongoDB, it is converted to a BSON object that is similar to a Ruby hash or JSON object.

The following code creates an instance of the Person model defined in the preceding section:

Person.create(name: 'Meena Kumar')

The document appears in MongoDB as follows:

{
"_id": {
"$oid": "673b6dce61700598c24a72b0"
},
"name": "Meena Kumar"
}

Note

_id Field

When you persist an instance of a model to the database, MongoDB automatically adds an _id field that has a unique value even if you do not explicitly define this field in your model.

To learn more about this field, see the ObjectId reference in the Server manual.

To learn more about the field types that you can use in Mongoid models, see the Field Types guide.

To learn how to access and change your MongoDB data, see the Interact with Data guides.

To learn more about how to model your data by using Mongoid models, see the Model Your Data guides.

Back

Model Your Data