its me
its me

Reputation: 542

how can i aggregate in mongodb?

I have two collections points collection and users collection here i want to do aggregation based on userid

  points collection           
{
    "userpoint": "2",
    "purchaseid":"dj04944",
    "store":"001",
    "date":ISODate("2017-11-10T08:15:39.736Z")
    "userid"[
    objectID("5a7565ug8945rt67"),
    objectID("8a35553d3446rt78")
    ]
},
{
    "userpoint": "4",
    "purchaseid":"5678sd",
     "store":"004",
    "date":ISODate("2017-11-11T08:15:39.736Z")
    "userid"[
     objectID("9a85653d3890rt09")
    ]
}

users collection

{
   objectID("5a7565ug8945rt67"),
   "name":"asdf",
   "mobinumber":"12345",

},
{
   objectID("8a35553d3446rt78"),
   "name":"qwr",
   "mobinumber":"11111",

},

{ objectID("9a85653d3890rt09"), "name":"juir", "mobinumber":"9611",

}

how can i do aggregation

db.points.aggregate([
    {
      $lookup:
        {
          from: "users",
          localField: "",
          foreignField: "",
          as: "inventory_docs"
        }
   }
])

i want to combine both collections help me out to move forward

Upvotes: 0

Views: 55

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

If your expected output like bellow

{
    "_id" : ObjectId("5a164fa5400096bfa0b3422c"),
    "date" : ISODate("2017-11-10T08:15:39.736Z"),
    "name" : "asdf",
    "mobile" : "12345"
}

The can try this query

db.points.aggregate([
{
    $match: {
      store: "001",
      date: {$lte: ISODate("2017-11-10T08:15:39.736Z"), $gte: ISODate("2017-11-10T08:15:39.736Z")}
    }
  },
  {$unwind: "$userid"},
  {
    $lookup: {
      from: "users",
      localField: "userid",
      foreignField: "_id",
      as: "user"
    }
  },
  {
    $project: {
      userpoint: 1,
      purchaseid: 1,
      date: 1,
      user: {$arrayElemAt: ["$user", 0]}
    }
  },
  {$match: {"user.name": "asdf"}},
  {
    $project: {
      date: 1,
      name: "$user.name",
      mobile: "$user.mobinumber"
    }
  }
])

Upvotes: 1

Related Questions