vinit
vinit

Reputation: 526

Indexing array of references using mongodb multikey indexing method in mongoose

My schema has an array of ObjectIds which are refs to another schema. What i want is to index this array entry using multikey indexing method of mongodb. So that given an ObjectId of some document in the ProductCat Collection, i can list all the documents in my current collection which has the given ObjectId in the _pro_cat field.

I am confused about the exact way in which i should declare the field, in mongoose schema declaration, Here is what i am trying:

_pro_cat: { type: [mongoose.Schema.Types.ObjectId], ref: 'ProductCat', index: true }

_pro_cat: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ProductCat', index: true }]

The name of this collection is Seller. I am making the relation, by using the reference in the schema and the actual field value is an array, each of type ObjectId, which will be the ObjectIds of the documents in the other Collection (ProductCat in this case). If i index this field i.e.. _pro_cat, then given an ObjectId of a document in ProductCat Collection, i would be able to find all the documents in the Seller collection which has given ObjectId in its array field _pro_cat.

I think i may have to call a separate index function. But i thought that this is a field level indexing so it may not be needed.

I suspect the later is only for sub-docs and not for refs. Would greatly appreciate, if anyone could shed some light on it. Thanks.

Side Question: [RE-SOLVED] In the mongodb documentation, it says that multikey indexing is automatic. multikey indexing. Does this mean that if that field is indexed, using the above methods, then mongo will recognize that the field is an array and use multikey indexing. OR does it mean that all the fields which are of array type will get indexed, without the need to explicitly telling it to index.

Thanks a lot.

related

Upvotes: 3

Views: 2925

Answers (1)

heinob
heinob

Reputation: 19464

Multikey Indexing means that every item in an array-field is indexed if you tell mongo to index the field.

It does not mean that all array fields are indexed automatically without the need to explicitely tell mongo to index the field.

Upvotes: 5

Related Questions