Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 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 Reply

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}  }} ]  
} }    
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...