1

I am new to Mongodb.i have two collections users and products.

In product collection user id is mapped.product collection has productid,producttype,productname and userid as fields.

i need to write aggregate query

  1. Use aggregate query to get all the products based on “product_type” and populate user (Aggregate query must be used)
  2. Use aggregate query to get all the product based on the user city (Aggregate query must be used)

var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("demo1");
  dbo
    .collection("products")
    .aggregate([{
        $match: {
          product_type: "$product_type"
        }
      },
      {
        $lookup: {
          from: "users",
          localField: "user_id",
          foreignField: "_id",
          as: "userdetails"
        }
      }
    ])
    .toArray(function(err, res) {
      if (err) throw err;
      console.log(JSON.stringify(res));
      db.close();
    });
});

I have tried this but not sure if this is right.

Please help.

1 Answer 1

1

what you have is correct for getting products by type. for getting products by user's city, give this pipeline a try:

db.products.aggregate([
{
  $lookup: {
    from: "users",
    let: { user_id: "$user_id" },
    pipeline: [
      { $match: {
          $expr: {
            $and: [ { $eq: [ "$_id", "$$user_id" ] },
                    { $eq: [ "$city", "new york" ] }]}}}],
    as: "user"
  }
},
{
  $match: {
    $expr: { $gt: [ { $size: "$user" }, 0 ] }
  }
}
])

test: https://mongoplayground.net/p/BebeOCd4wLQ

update: here's another way:

db.products.aggregate([
    {
        $lookup: 
        {
            from: "users",
            localField: "user_id",
            foreignField: "_id",
            as: "user"
        }
    },
    {
        $match: {
            "user.city": "new york"
        }
    },
    {
        $project: {
            user: 0
        }
    }
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.