Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

mongodb - Aggregating records by $group - condition 1 or condition 2

I have a database of about 50k "company" records.

I want to find duplicates by matching:

  1. name and street fields.

OR

  1. phone field

(I consider both #1 and #2 unique identifiers, so either can be used to find duplicates.)

I am able to write the $group statement to match based on #1:

  _id: {
    name: '$name',
    street: 'street'
  },
  uniqueIds: {
    $addToSet: '$_id'
  },
  count: {
    $sum: 1
  }

I tried something like this to match one or the other:


_id: { 
 $or: [
  {name: '$name', street: '$street'},
  {phone: '$phone}
 ]
}...

But that just returns a boolean.

How to group by filtering for #1 or #2 above in the same aggregation?

question from:https://stackoverflow.com/questions/66054071/aggregating-records-by-group-condition-1-or-condition-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option is to use $facet:

db.company.aggregate([  
{ $facet:{  
by_name_street:[ {$group:{ _id:{n:"$name",str:"$street" }, cnt:{$sum:1} }} ] , 
by_phone:[ {$group:{ _id:"$phone" , cnt:{$sum:1}  }} ]  
} }    
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...