Distinct() on indexed field returns undefined

71 views
Skip to first unread message

en...@hrs-pd.de

unread,
Feb 3, 2018, 2:01:28 AM2/3/18
to mongodb-user
Hi,

In one collection we have documents which look like this:

{
   
"A" : [],
}

OR

{
       
"A" : [
       
{
           
"_id" : 1,
           
"Name" : "ASDF"
       
},
       
{
           
"_id" : 2,
           
"Name" : "GHJKL"
       
}
   
],
}



So we need all the distinct values of this array for our UI.
Running
db.getCollection('X').distinct('A')

actually works fine and returns the values we expect. If we then add an index on this Field ( db.X.createIndex({"A":1,{Name:"IX_A"}) and run this query again, there is suddenly an item undefined:
[
   
undefined,
   
{
       
"_id" : 1,
       
"Name" : "ASDF"
   
}, ...
]



So how can we get rid of this undefined item in the index?

Thanks!


Wan Bachtiar

unread,
Mar 8, 2018, 10:13:01 PM3/8/18
to mongodb-user

actually works fine and returns the values we expect. If we then add an index on this Field ( db.X.createIndex({“A”:1,{Name:”IX_A”}) and run this query again, there is suddenly an item undefined:

Hi,

Depending on your use case, Partial Indexes is likely what you’re after.
For example you can create:

db.collection.createIndex({"A":1}, {partialFilterExpression:{"A":{"$exists":true}}})

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages