开发者

Mongo Query array, when array key is unknown?

I have following in the database, and I like to find this item with a the search term "open"

It should almost be something like this, I guess???

 $query = array(array('keywords' => array('$in'=>'open')));
 $cursor = $collection->find($query);
 return iterator_to_array($cursor);

In Database:

[3b33162ad4ed5ffdeb88a1b2085535b1] => Array
    (
        [_id] => 3b33162ad4ed5ffdeb88a1b2085535b1
        [title] => Something
        [keywords] => Array
            (
                [2] => open
                [7] => source
            )

        [added] => MongoDate Object
            (
                [sec] => 1305884144
   开发者_开发百科             [usec] => 658000
            )

    )


The problem you're having is the structure of your data.

MongoDB natively works with arrays when querying. The following will work.

$document = array( 'keywords' => array('open', 'source') );
$collection->insert($document);
$collection->find( array('keywords' => 'open') );

The problem you have is that keywords is not an array in your document. In your document keywords is another document.

'keywords' => array( '2' => 'open',
                     '7' => 'source' )

In JSON this would look like this:

{ 'keywords' : { '2': 'open', '7': 'source' } };

Based on what you're trying to do you need to save keywords as an array and not as a hashtable.

In PHP it's not always obvious which you're dealing with at code time. However, if you print_r an array, it will look like the following. Notice the array is zero-based and is not missing any keys.

    [keywords] => Array
        (
            [0] => open
            [1] => source
            [2] => rules
        )


You can query Arrays in MongoDB like normal values. Here an example in the JavaScript Shell.

> db.php.insert({title: "something", keywords: ["foo","bar"]})
> db.php.insert({title: "something", keywords: ["open","bar"]})
> db.php.insert({title: "something", keywords: ["baz","faz"]})
> db.php.find({ keywords: "open" });
{ "_id" : ObjectId("4dd677229a547d85bb02fce5"), "title" : "something", "keywords" : [ "open", "bar" ] }

For Faster Queries you should create an index on the array.

db.php.ensureIndex({keywords: 1})

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜