Jonathan Clark
Jonathan Clark

Reputation: 20538

How to create a multi level document using MongoId

I am developing a Ruby on Rails (3.2.6) application and is using MongoId (3.0.0) to interact with the MongoDB database. I am just wondering how do save embeded JSON objects that contains multiple levels and not just one level.

I got an old MongoDB database with this and simular structure so I need to save new documents using the same structure.

This is from the documentation and is used to add a one level document:

Person.create(
  first_name: "Heinrich",
  last_name: "Heine"
)

How can I add an object with this structure:

{
    "basic": {
        "file_id": {
            "file": "cf1952761a806c56c9bee60665418f02c"
        },
        "share": false,
        "status": "created"
    },
    "data": {
        "id": "4fd942dder5f5e88837300026e",
        "name": "roberta",
        "comment": "This is a comment"
    }
}

Upvotes: 1

Views: 402

Answers (1)

Baruch
Baruch

Reputation: 1133

The easiest way to do this is to create classes for basic and data and embed them in your top level document.

Embedded document classes are defined in Mongoid the same way as other documents with an embedded_in call and a matching embeds_one or embeds_many in the top level document.

The other option is to simply define a Hash field, but this obviously may have any structure.

Class Person
    include Mongoid::Document

    field :data, :type => Hash

    ...
end

:data will accept any hash, even with nested hashes.

Upvotes: 2

Related Questions