Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb - "join" or $in two collections

Suppose I have 2 collections:

> db.fellas.findOne()
{
    "_id" : 123
    "women" : [
        1,
        12,
        34
    ]
}

> db.women.findOne()
{ "_id" : 12, "busty" : 1 }

Some of the women belong to a certain fella, but some of them don't. In the case above, the woman does belong to the fella.

How do I find all women whose don't belong to any fella? I tried to do that using $unwind, but no luck. I mean, I'm unaware what I should do further.

Your ideas?

like image 384
Alan Coromano Avatar asked Jan 21 '26 11:01

Alan Coromano


1 Answers

You can use a function like the following one:

db.women.find().forEach(function(w){
  if( !db.fellas.findOne({ women:{$in:[w._id]} }) )
    printjson(w); 
)}

There is another way, namely mapreduce.

like image 59
Muatik Avatar answered Jan 25 '26 19:01

Muatik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!