Exclude _id field during a join query

Viewed 86

I try to create a join query and exclude _id field from my result

    stage_lookup_comments = {
        "$lookup": {
                "from": "products",
                "localField": "product_codename",
                "foreignField": "codename",
                "as": "product",
        }

    }

    pipeline = [
        { "$match": {
            "category":category,
            "archived_at":{"$eq": None}
            }
        },
        stage_lookup_comments
        ]

    array = await db[collection].aggregate(pipeline).to_list(CURSOR_LIMIT)
    return array

I don't know what is the syntax to add the "_id": 0 parameter to my query.

1 Answers

You should be able to use MongoDB $project in your pipeline to select only those fields you want to return. In this particular case you can exclude _id field as you already mentioned putting _id:0.

Read documentation about $project here for more details.

I didn't test it, but your query should be something similar to the following:

stage_lookup_comments = {
        "$lookup": {
                "from": "products",
                "localField": "product_codename",
                "foreignField": "codename",
                "as": "product",
        }

    }

    pipeline = [
        { 
          "$match": {
             "category":category,
             "archived_at":{"$eq": None}
           }
        },
        stage_lookup_comments,
        { 
           $project: { "_id": 0 } 
        }

    ]

    array = await db[collection].aggregate(pipeline).to_list(CURSOR_LIMIT)
    return array


EDIT:

Also, starting in MongoDB 4.2, you can use operator $unset to explicitly remove a field from a document (see documentation here):

{ $unset: ["_id"] }

You can read more about this in this very similar question here on Stackoverflow. I hope this works!

Related