Reputation: 4491
Say I have a collection that has documents like this where the crossRefs field is an array of strings:
{ name: "joe", crossRefs: [ "1" , "2" , "10a"] }
{ name: "jane", crossRefs: [ "10a" , "0xfgh" , "9"] }
{ name: "john", crossRefs: [ "11" , "hhj12" , "13dd"] }
...
Question 1: How to build a query against crossRefs with an array of strings
I would like to have a query that says "give me all the documents that have any one of crossRefs '10a', '1' and '2'". So the result from the above 3 documents would be just the first 2. I'm thinking I need $elemMatch
or $in
with a combination of or
s but I just don't know how to formulate this.
Question 2: How to specify an index
I would like for MongoDB to build an index based on the crossRefs field. In Java is this as simple as:
mainDB.getCollection("theCollection").ensureIndex("crossRefs");
I.e. does that work ok when the field is actually an array of strings?
Thanks in advance.
Upvotes: 0
Views: 859
Reputation: 312149
$in
works with array fields as well as non-array fields, so in the shell it would be:
db.theCollection.find({crossRefs: {$in: ['10a', '1', '2']}})
This will find the docs where at least one crossRefs
element matches an $in
element.
And yes, that's the correct way to index the field, even when it's an array.
Upvotes: 2