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.

3 Answers 3

2

It depends on how you want this formatted but here is a aggregation version which formats it in a nice way:

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

It will print documents like:

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

Another way could be to just project the single field out with $db->collection->find(array(),array('content.id'=>1))

I should note though, it would most likely to better to just do this in PHP. Through PHP is the only way you can get the exact output you are seeking I believe.

Sign up to request clarification or add additional context in comments.

2 Comments

@MaximShoustin True, converted to PHP
@MaximShoustin There is a serious troll some where, I get a lot of answers downvoted recently, it is rather annoying :/
2

Try this:

$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);

Comments

1

Use mapreduce followed by distinct, as follows:

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", ...]

Or use Variety...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.