Anurag Sharma
Anurag Sharma

Reputation: 5039

get distinct items in a collection if other item is not null

I have a collection like this

{
Country : 'XYZ'
Books : [
         {"name" : "book1", "url" : "book1url", "auth_email" : "emailid1"},
         {"name" : "book2", "url" : "book2url", "auth_email" : "emailid2"},
         {"name" : "book3", "url" : "book3url", "auth_email" : "emailid3"},
         {"name" : "book4", "url" : "book4url", "auth_email" : "emailid4"}
         ..........................................
       ]

}

I want to extract
distinct 'Books.name' and corresponding 'Books.email'
only if
'Books.email' is not = ''

Upvotes: 0

Views: 200

Answers (1)

Sammaye
Sammaye

Reputation: 43884

Unfortunately the easiest way I can come up with the at the moment is to unwind the Books array, match only those that have an email value and then form the root documents back up:

db.collection.aggregate([
    {$unwind:'$Books'},
    {$match: {'Books.auth_email':{$nin:['',null]}}},
    {$group: {_id:'$Books.name',email:{$first:'$Books.auth_email'}}}
])

Though another way which should work as well:

db.collection.aggregate([
    {$unwind:'$Books'},
    {$match: {'Books.auth_email':{$nin:['',null]}}},
    {$group: {_id:'$_id',Country:'$Country',Books:{$addToSet:'$Books'}}}
])

I believe that in python you can just do:

self.mongo.aggregate([
    {"$unwind":"$Books"},
    {"$match": {"Books.auth_email":{"$nin":['',null]}}},
    {"$group": {"_id":"$Books.name","email":{"$first":"$Books.auth_email"}}}
])

Upvotes: 1

Related Questions