Haris Hajdarevic
Haris Hajdarevic

Reputation: 1575

Query in mongo with $in operator

I have one collection which contain documents with following structure:

array (
  '_id' => new MongoId("54369e2904f7055598463483"),
  'user' => '123',
  'model' => 
  array (
    'test' => 
    array (
      '0' => 'test1',
      '1' => 'test2',
      '2' => 'test3',

    ),
  ),
)

And if I do the next query in Rock Mongo I got the results.

array(
 'user' => array(
  '$in' => array(
    '0' => '123'
    )
 )
)

But if I try to fetch documents which have for example key => pair value '0' => 'test1' & '1' => 'test2' I don't get any data with the next query:

array(
 'model' => array(
    'test' => array(
  '$in' => array(
    '0' => 'test1',
    '1' => 'test2',
    )
 )
 )
)

Where I'm making mistake?

Thanks in advance

Upvotes: 1

Views: 1000

Answers (1)

Max Noel
Max Noel

Reputation: 8910

PHP's array/hash mixup makes your example a little hard to read and reason about. But here's what your model looks like in Mongo's native syntax (a language which makes a distinction between lists and maps):

{
    "_id": ObjectId(...),
    "user": 123,
    "model": {"test": ["test1", "test2", "test3"]}
}

So you want to query on model.test (nested document). Using Mongo's native syntax, you'd do the following:

collection.find({"model.test": {"$in": ["test1", "test2"]})

See http://docs.mongodb.org/manual/reference/method/db.collection.find/ for more info.

Upvotes: 2

Related Questions