jlazevedo
jlazevedo

Reputation: 82

MongoDB: find documents that contain a certain value in one of its fields

Sorry about the title...

I have a mongoDB collection like this:

{
 students: [1, 2, 3],
 teachers: [4, 5]
},
{
 students: [5, 6, 7, 8, 9],
 teachers: [10]
},
{
 students: [11, 12, 14, 15, 16],
 teachers: [17, 18]
 supervisor: [5]
}

Let's say that "1", "2", "..." identifies someone who is a teacher or a student or something else. What I want to do is find documents that contain subject 5.

Is this possible without querying explicitly field by field (students, teachers, supervisor)?

Thanks ;)

Upvotes: 1

Views: 163

Answers (2)

Neil Lunn
Neil Lunn

Reputation: 151072

When using arrays you are bound by the constraints of multi-key indexes. So you cannot possibly create a compound index that has more than one "array" type of element. So that rules out methods where you can span multiple fields in a search. Such as text search.

You must specify all fields, but you can do this with an $or condition:

db.collection.find({ 
    "$or": [
        { "students": 5},
        { "teachers": 5 },
        { "supervisor": 5 }
    ]
})

Of course you could look at ways to determine the "fields" that you need to include in this way, or otherwise suffer the sort of JavaScript scanning you can do with mapReduce.

Upvotes: 1

hellboy
hellboy

Reputation: 2252

Check the documentation on TextIndex. If you create a TextIndex you can search through multiple attributes. But while creating the index you need to include all the attributes which needs to be searched. You can also provide weights on each attribute, so that Mongo can order the result depends g on which attribute matched the value.

Edit - ruling out text edit based on Neil 's comment. Can you try creating single Index on each attribute and then use an OR clause with all the attributes? OR will make use of all the single indexes. Performance will depend upon the number of attributes.

Upvotes: 1

Related Questions