سؤال

I know that a compound index is defined like this:

db.products.ensureIndex( { "item": 1, "stock": 1 } )

and a hashed a simple index like this:

db.active.ensureIndex( { item: "hashed" } )

question is how to achieve both?

هل كانت مفيدة؟

المحلول

According to the hashed index documentaion You can't!

MongoDB supports hashed indexes of any single field. The hashing function collapses sub-documents and computes the hash for the entire value, but does not support multi-key (i.e. arrays) indexes.

You may not create compound indexes that have hashed index fields

PS: The above is valid for versions 2.4 and 2.6 (which is the latest at the moment)

PS2: According to @naman's answer it is now possible in version 4.4

نصائح أخرى

If you want to achieve a compound hashed index, it's feasible with version 4.4 and above. From the documentation, you can now create it as:

db.adminCommand( { setFeatureCompatibilityVersion: "4.4" } )
db.collection.createIndex( { "fieldA" : 1, "fieldB" : "hashed", "fieldC" : -1 } )

for the particular example in question

db.products.ensureIndex( { "item": "hashed", "stock": 1 } )

MongoDB 4.4 support compound index with single hashed which can be created like

db.collection.createIndex( { "colA" : 1, "fieldB" : "hashed" } )

Note: Make sure featureCompatibilityVersion set to 4.4 so that you can create compound hashed index.

db.adminCommand( { setFeatureCompatibilityVersion: "4.4" } )

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top