I’m trying to link one document to another. To do that, I’m trying to store the ObjectID of one document in the other. I’m trying a couple of different ways that should produce the same results, but they actually look different. Here are the ways I’m trying:
Method 1
owner['ownedCar'] = db.cars.find_one({ '_id' : ObjectId( $theCarsObjectIDstring ) }, {'_id': 1})
db.owners.save(owner)
which looks like this in the database:
{
_id {"$oid": "502186421fe3321dfa000001"}
}
and Method 2
car = db.cars.find_one( { '_id' : ObjectId( $theCarsObjectIDstring ) } )
owner['ownedCar'] = car['_id']
db.owners.save(owner)
which looks like this:
{"$oid": "502186421fe3321dfa000001"}
Shouldn’t they look the same? What’s the preferred way to link documents?
EDIT Why is this question getting downvoted?
These two results are the same, the difference is how you are picking out the results to populate the linked field.
When you use the second param of
findto return fields, even if it is just one it will always return an object with the field names as the keys and the field values as the value. You make the linked field equal that object as such you don’t just get the ID back as the value of the linked field. So the result of your first query is:And you make the field equal that.
Alternatively you are physically picking out
car['_id']in the second query as such the value of the linked field is just the id.This is a driver and language difference in interpretation of how it should return values.
I would say the second method is the best way since the first adds unnessecary bloat to the field in the form of the extra object.