0

How can I define ref and how to query a collection with ref populating related fields.

I defined a ref when inserting a product document in a product collection, but when querying I am getting info as inserted without populating the category field. I am expecting the mongo to populate category field with category document in category collection. The following are some code snippets:

Document Insertion:

category = "5126bc054aed4daf9e2ab772"
product_name = "Prod"
new_product_id = mongo.db.product.insert_one({
    "product_name": product_name,
    "category": {
        "$ref": "category",
        "$id": ObjectId(category)
    }
}).inserted_id

Results Obtained:

{
    "_id": {
        "$oid": "61dd1612b898afc16e0f4325"
    },
    "category": {
        "$id": {
            "$oid": "5126bc054aed4daf9e2ab772"
        },
        "$ref": "category"
    },
    "product_name": "Prod"
}
Valentine Sean
  • 79
  • 3
  • 13

1 Answers1

0

I think you can try the below code, I feel it will work

category = "5126bc054aed4daf9e2ab772"
product_name = "Prod"
new_product_id = mongo.db.product.insert_one({
    "product_name": product_name,
    "category": category
}).inserted_id
Anuj Panchal
  • 391
  • 3
  • 15