1

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.

Howins
  • 487
  • 1
  • 6
  • 18
  • How about adding one more `$project` stage at the end to exclude the `_id` field through `_id: false`? – ray Dec 10 '21 at 16:28

1 Answers1

0

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!

Emiliano Viotti
  • 1,619
  • 2
  • 16
  • 30