1

I'm new in mongoDB, I saw enough examples but most show how to work with collections.

I have followed data stored in mongoDB under DB name myDB:

"_id" : "some_table_name",
"content" : [{
  "id" : "1",
  "loctype" : "Clinic/Hospital",
  "locname" : "KKH"
}, {
  "id" : "2",
  "loctype" : "Clinic/Hospital",
  "locname" : "Singapore National Eye Centre"      
 }
 }]
}

As you can see the model contains _id and content, where content is list of objects:

  ... ,
 {
  "id" : "ZZZ",
  "loctype" : "ZZZ",
  "locname" : "ZZZ"      
  },
  ...

PHP

$m = new MongoClient(/* ... */);

$db = $m->myDB;

$collection = $db->coll;

How can I fetch in PHP list of ids? a.e [1,2] in my case.

For sure I can get all model and extract ids but I try to do it stright from mongoDB.

Thanks.

4

3 回答 3

2

这取决于您希望如何格式化,但这里有一个聚合版本,它以一种很好的方式格式化它:

$mongo->collection->aggregate(array(
    array('$unwind'=>'$content'),
    array('$project'=>array('_id'=>'$content.id'))
))

它将打印以下文件:

[
    {_id:1},
    {_id:2}
]

另一种方法可能是使用$db->collection->find(array(),array('content.id'=>1))

不过我应该注意,在 PHP 中执行此操作很可能会更好。我相信,通过 PHP 是获得所需输出的唯一方法。

于 2013-05-28T10:52:14.553 回答
2

尝试这个:

$collection = new MongoCollection($db, 'collection_name');

$query = array(
// Some restrictions can be here
);

$ids    = array();
$cursor = $collection->find($query);
foreach ($cursor as $doc) {
    $doc = (array) $doc;
    $ids[] = $doc["id"];
}

var_dump($ids);
于 2013-05-28T10:50:26.617 回答
1

使用 mapreduce 后跟 distinct,如下:

mr = db.runCommand({
  "mapreduce" : "things",
  "map" : function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce" : function(key, stuff) { return null; }, 
  "out": "things" + "_keys"
})
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]

或者使用品种...

于 2013-05-28T11:20:42.853 回答