3

In MongoDB there is a nice tutorial on Manual Reference:

Example:

original_id = ObjectId()

db.places.insert({
    "_id": original_id,
    "name": "Broadway Center",
    "url": "bc.example.net"
})

db.people.insert({
    "name": "Erin",
    "places_id": original_id,
    "url":  "bc.example.net/Erin"
})

Note, that this two documents are created at same time.

Question. I need to reference a Customer with an Order, therefore the Customer has been created long time before the Order, how can I add this reference of customer and insert in Order?

Naga Kiran
  • 8,585
  • 5
  • 43
  • 53
Danystatic
  • 71
  • 9
  • I don't see how your example connects with your question? – mjhm Jan 20 '13 at 05:50
  • okay, what about this: I already do this with help from DaveCosta: > db.orders.find().pretty() { "_id" : ObjectId("50fbb887f577c8c2609c7130"), "order" : "1", "customer" : { "_id" : ObjectId("50fba0b4d7bc28cd6a72393d"), "name" : "daniel" } } { "_id" : ObjectId("50fbb8def577c8c2609c7131"), "order" : "2", "customer" : { "_id" : ObjectId("50fba0b4d7bc28cd6a72393d") } } I guess it is complete for now! – Danystatic Jan 20 '13 at 07:37

1 Answers1

2

Wouldn't you need to do a findOne() on your customer first and add it's id property to your new document?

DaveStSomeWhere
  • 2,475
  • 2
  • 22
  • 19
  • oh!!! it has worked! do you know why it will not work with find(), but yes! it works with findOne() thankyou! I would appreciate if you answer this question too. – Danystatic Jan 20 '13 at 06:17
  • 1
    Here's a quote from a MongoDB person regarding the difference between find() and findOne() - hope this helps:`The two queries you are executing are very different. A find query returns a cursor, this is essentially a no-operation scenario, as no actual data is returned (only the cursor information). If you call findOne, then you are actually returning the data and closing the cursor. The docs should definitely be clearer :-)` – DaveStSomeWhere Jan 20 '13 at 06:25
  • thanks, now I have my referenced object: (two types) 1. { "_id" : ObjectId("50fbab64d7bc28cd6a723943"), "order" : "2", "customer" : ObjectId("50fba0b4d7bc28cd6a72393d") } 2. { "_id" : ObjectId("50fbaeefd7bc28cd6a723944"), "order" : "9", "customer" : { "_id" : { "_id" : ObjectId("50fba0b4d7bc28cd6a72393d") } } } This is the orders document. I am having trouble querying by customer. Can you help? How can I query by 'customer'? – Danystatic Jan 20 '13 at 06:50
  • got it! after many attempts the easiest way was the solution. I have seen your website, cool – Danystatic Jan 20 '13 at 07:16