John
John

Reputation: 4981

MongoDB lookup get referenced object id and advice for reference

I'm using PyMongo and MongoDB 4.0.1. For the example I'll call my collections User and Car. So my user can get only one car (One to One relationship)

User
----
_id : ObjectId("2b2543b24713ea82ce3ae21f")
Firstname : John
Lastname : Doe
Car : ObjectId("5b854bb806a77a06ce321f1f")

Car
----
_id : ObjectId("5b854bb806a77a06ce321f1f")
Model : Tesla Motor

When I do this query :

db.user.aggregate(
  {$unwind: "$car"},
  {$lookup: {
    from:"car",
    localField: "car",
    foreignField: "_id",
    as: "car"
   }}
)

the output show me that car property will be an array of cars with one object...

{ 
  "_id" : ObjectId("2b2543b24713ea82ce3ae21f"), 
  "firstname" : "John", 
  "lastname" : "Doe" , 
  "car" : [ { 
      "_id" : ObjectId("5b854bb806a77a06ce321f1f"), 
      "model" : "Tesla Motor"
   }] 
}

It's possible to get just one object and not an array ?

Another question about references. Lot of different Users can get the same car. It is good in No SQL database to reference the object id or it's better to create all car fields in the User collection ? Because I have to update all different data. For example if there is a change on the Car I think it's easier to update just one document in the Car collection than update 50 rows in the user collection.

Do you think I'm right ?

Upvotes: 3

Views: 3399

Answers (1)

Ashh
Ashh

Reputation: 46441

You need to use the $unwind after the $lookup stage

db.user.aggregate([
  { "$lookup": {
    "from": "car",
    "localField": "car",
    "foreignField": "_id",
    "as": "car"
  }},
  { "$unwind": "$car" }
])

Upvotes: 4

Related Questions