Kevin Meredith
Kevin Meredith

Reputation: 41909

Querying Mongo across Two Arrays

Let's say I have the following document structure:

{ _id : 1,
  items: [ {n: "Name", v: "Kevin"}, ..., {n: "Age", v: 100} ],
  records : [ {n: "Environment", v: "Linux"}, ... , {n: "RecordNumber, v: 555} ]
}

If I create 2 compound indexes on items.n-items.v and records.n-records.v, I could perform an $all query:

db.collection.find( {"items" : {$all : [{ $elemMatch: {n: "Name", v: "Kevin"} },
{$elemMatch: {n: "Age", v: 100} } ]}})

I could also perform a similar search on records.

db.collection.find( {"records" : {$all : [{ $elemMatch: {n: "Environment", v: "Linux"} },
{$elemMatch: {n: "RecordNumber", v: 555} } ]}})

Can I somehow perform a query that uses the index(es) to search for a document based on the items and records field?

find all documents where item.n = "Name" and item.v = "Kevin" AND record.n="RecordNumber" and record.v = 100

I'm not sure that this is possible using $all.

Upvotes: 0

Views: 297

Answers (1)

SuperAce99
SuperAce99

Reputation: 722

You can use an index to query on one array, but not both. Per the documentation, While you can create multikey compound indexes, at most one field in a compound index may hold an array.

Practically:

  • You can use a Compound index to index multiple fields.
  • You can use a Multikey index to index all the elements of an array.
  • You can use a Multikey index as one element of a compound Index
  • You CANNOT use multiple multikey indexes in a compound index

The documentation lays out the reason for this pretty clearly:

MongoDB does not index parallel arrays because they require the index to include each value in the Cartesian product of the compound keys, which could quickly result in incredibly large and difficult to maintain indexes.

Upvotes: 2

Related Questions