Cjoerg
Cjoerg

Reputation: 1325

How to create a relation between 2 documents in MongoDB?

I have a Ruby on Rails application that usually communicates with MongoDB through the Mongoid gem, but for performance reasons I need to insert documents directly into MongoDB like this:

Order.collection.insert(Array.new << {order_id: order_id, mail_address: mail_address}) # this creates the document, but does not return anything useful that can be referenced: {"n"=>0, "connectionId"=>53675, "wtime"=>0, "err"=>nil, "ok"=>1.0}

Customer.collection.insert(Array.new << {mail_address: mail_address})

I have defined a relationshop where a Customer has many Orders, so if I used Mongoid I could create the relation with customer.orders << order.

But how do I create the relation when I'm not using Mongoid?

Upvotes: 0

Views: 64

Answers (1)

mu is too short
mu is too short

Reputation: 434665

None of Moped's insert methods return anything terribly useful to you so your documents are getting normal ObjectId's in their _id but you have no easy way of knowing what they are. You're on the right track by trying to assign your own _ids but you don't have to use Strings, you can simply say Moped::BSON::ObjectId.new to generate a new _id. Assuming that your Orders have a customer_id which points at the Customer, you could:

customer_id = Moped::BSON::ObjectId.new
Customer.collection.insert(_id: customer_id, mail_address: mail_address)
Order.collection.insert(customer_id: customer_id, ...)

Don't be afraid to poke around inside MongoDB using the mongo shell to see how things are structured internally. All the helpful relations and embedding conveniences that Mongoid provides are nice but you still need to know what they're doing to your database.

Upvotes: 1

Related Questions