Mukul Anand
Mukul Anand

Reputation: 626

How to create index for the following kind of data in mongodb

db.test.insert({a:1, b:[1])
db.test.insert({a:1, b: 1})
db.test.insert({a:[1], b: 1})
db.test.insert({a:[1], b: [1]})

what should be a right way to index the fields so that i can query over a and b?

Upvotes: 0

Views: 23

Answers (1)

John
John

Reputation: 2761

{ _id: 1, a: [1, 2], b: 1, category: "A array" }
{ _id: 2, a: 1, b: [1, 2], category: "B array" }

A compound multikey index { a: 1, b: 1 } is permissible since for each document, only one field indexed by the compound multikey index is an array; i.e. no document contains array values for both a and b fields.

However, after creating the compound multikey index, if you attempt to insert a document where both a and b fields are arrays, MongoDB will fail the insert.

---- Documentation

But one of your doc's a & b both contain array.

Upvotes: 1

Related Questions