Prabjot Singh
Prabjot Singh

Reputation: 4767

Mongodb: Get count of common documents based on the field value

Suppose i have a collection of documents,something like this:

{
"itemName":"Burger",
"userId":"25286",
"location":{
       "locationTitle":"Burger king,Delhi"
   }
}

{
"itemName":"Burger",
"userId":"25287",
"location":{
       "locationTitle":"Burger king,Delhi"
  }
}

I have to find common items between two users. Item will be common if one of field itemName or locationTitle have same field value. But one user can have more then one items having same name.

Thanks

Upvotes: 1

Views: 1212

Answers (1)

White Bullet
White Bullet

Reputation: 215

You can use aggregation to group the common items together. The two queries below group entries if they have the same itemName or locationTitle, and adds the userIds to a users array. users array will not contain duplicates, therefore, takes into consideration the requirement that the userId should not be added twice if the same entry appears more than once.

db.items.aggregate({
  $group: {
    _id: "$itemName",
    users: {
      $addToSet: "$userId"
    },
    count: {
      $sum: 1
    }
  }
});

db.items.aggregate({
  $group: {
    _id: "$location.locationTitle",
    users: {
      $addToSet: "$userId"
    },
    count: {
      $sum: 1
    }
  }
});

Upvotes: 2

Related Questions