Home > Enterprise >  Mongoose filter object in field_name
Mongoose filter object in field_name

Time:09-22

enter image description here

I want to list cars by username, how can i do?

CodePudding user response:

For filtering documents from another document, you need to use populate the field.

For this, we are using aggregate. In lookup ; we are connect the cars field with user field to reach user field's values as username etc.

In MongoDB Compass, you need to use MONGOSH at the left bottom of the page. Firstly, need to achieve the database you want to make filter on. For this,

use arpaslanOto

Now, you switched your DB. Current db is alparslanOto. Then write the filters you want to search on the field as;

db.cars.aggregate([
          {
            $lookup: {
              from: "users",
              localField: "user",
              foreignField: "_id",
              as: "UserCarTable",
            },
          },
          {
            $match: { "UserCarTable.username": username },
          },
        ];
    )

I hope, it's useful for you

CodePudding user response:

enter image description here

With the method you suggested, the response returns empty.

-Response from below codes

enter image description here

CodePudding user response:

 db.cars.aggregate([
        {
          $lookup: {
            from: "users",
            localField: "user",
            foreignField: "_id",
            as: "cars",
          },
        },
        {
          $match: { "cars.name": "Mustafa" },
        },
      ])

Working!!

  • Related