Python – MongoDB lookup get referenced object id and advice for reference

MongoDB lookup get referenced object id and advice for reference… here is a solution to the problem.

MongoDB lookup get referenced object id and advice for reference

I’m using PyMongo and MongoDB 4.0.1. For example, I’ll call my collections User and Car. So my users can only get 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 execute this query:

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

The output shows that the car property will be a set of cars with one object….

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

Is it possible to get only one object instead of an array?

Another question about citations. Many different users can get the same car. Is it better to reference the object ID in the No SQL database, or is it better to create all car fields in the User collection? Because I have to update all the different data. For example, if Car changes, I think it’s easier to update only one document in the Car collection than to update 50 rows in the user collection.

Do you think I’m right?

Solution

You need to use $unwind $lookup > Subsequent phase

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

Related Problems and Solutions