简体   繁体   English

如何在mongodb的字段中找到多个项目?

[英]How do I find multiple items in a field with mongodb?

I have the following type of occurrence in my Mongo documents. 我的Mongo文档中出现以下类型的事件。

"tags" : [ [ "narnia" ], [ "aslan" ], [ "winter" ], [ "heaven" ] ]

I need to know how to find this document by matching all of any number of the tags. 我需要知道如何通过匹配所有数量的标签来查找此文档。 Ie Narnia AND Aslan (but not Narnia OR Aslan). 即纳尼亚和阿斯兰(但不是纳尼亚或阿斯兰)。

The query needs to be made with in PHP. 该查询需要使用PHP进行。

So far I only have it working for a single tag. 到目前为止,我只对单个标签起作用。 Ie

$filter['tags'] = array('$in' => array(array('Narnia')));

As Hussain mentioned in comments - you might want to revise that document structure as seems like you're storing unnecessary arrays. 正如侯赛因在评论中提到的那样,您可能希望修改该文档结构,就像您正在存储不必要的数组一样。

Otherwise, what you're trying to do could be done with an $and statement (example without the nested arrays): 否则,您可以尝试使用$and语句(不带嵌套数组的示例)完成操作:

PRIMARY> db.wardrobe.find({ $and: [ { tags: "narnia" }, { tags: "tugboat" } ] })
//returns nothing

PRIMARY> db.wardrobe.find({ $and: [ { tags: "narnia" }, { tags: "winter" } ] })
//returns { "_id" : ObjectId("521067a48202463b88c2a0c9"), "tags" : [ "narnia", "aslan", "winter", "heaven" ] }

In PHP: 在PHP中:

//With your nested arrays:
$filter = array(
   '$and' => array( 
      array('tags' => array('narnia') ), 
      array('tags' => array('aslan') )
   )
);

//With a simple array:
$filter = array(
   '$and' => array( 
      array('tags' => 'narnia'), 
      array('tags' => 'aslan')
   )
);

$mongoClient->selectCollection('cwlewis', 'wardrobe')->find( $filter );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM