我在Mongo中创建了一个"params"集合,结构如下:
{
"_id" : "id1",
"list" : [
{
"type" : "type1",
"subtypes" : [ "id1 subtype11", "id1 subtype12" ]
}
{
"type" : "type2",
"subtypes" : [ "id1 subtype21", "id1 subtype22" ]
}
]
}
{
"_id" : "id2",
"list" : [
{
"type" : "type1",
"subtypes" : [ "id2 subtype11", "id2 subtype12" ]
}
{
"type" : "type2",
"subtypes" : [ "id2 subtype21", "id2 subtype22" ]
}
]
}
我想得到"_id":"id1"
和"type":"type1"
的所有"subtypes"
。我发现在Mongo shell中这样做的方法是
db.params.find (
{ $and: [
{"_id" : "id1"},
{"list.type" : "type1"}
] }
)
我有两个问题:
- 我是否使用$和(读:"我正在创建查询")正确的方式?
- 如何解析这个查询PHP代码正确?我被语法弄糊涂了:(.
谢谢!
事实证明,回答这个问题的PHP代码实际上并不难:
$query = array('_id' => 'id1', 'list.type' => 'type1');
$result = $collection->find($query);
/* Use this to access each element of the results */
foreach($result as $doc) {
/* Code goes here */
}
如果想要使用"type"
中的每个值(例如打印它们),代码将是:
$output = [];
$query = array('_id' => 'id1');
$field = array('list.type' => true);
$result = $collection->find($query, $field);
foreach($result as $doc) {
foreach($doc['list'] as $elem) {
$output[] = $elem['type'];
}
}
通过对每个文档使用var_dump()
函数并分析输出,我发现了所有这些。希望这对像我一样的初学者有所帮助。感谢Sammaye的建议!:)
$collection->find(array(), array('USERS.TASKS. ')。MISSION_SAS_ID' => true));
使用上面的代码获取子文档数据