php mongodb 中的投影

projection in php mongodb

我有一个集合,其中包含类似

的文档
{
 "_id": ObjectId("5b4dd622d2ccda10c00000f0"),
 "Code": "Route-001",
 "Name": "Karan Nagar - Jawahar Nagar",
 "StopsDetails": [
  {
   "StopId": "cb038446-bbad-5460-79f7-4b138024968b",
   "Code": "Stop- 001",
   "Name": "Lane market",
   "Fee": "600" 
  },
  {
   "StopId": "2502ce2a-900e-e686-79ea-33a2305abf91",
   "Code": "Stop-002",
   "Name": "City center",
   "Fee": "644" 
  }
 ],
  "StopsTiming" :
   [
       ....
   ] 
}

我只想获取所有嵌入文档 "StopDetails"。我正在尝试调整以下代码行,但我无法在 $query "StopsDetails" 中写入内容,以便仅获取 StopsDetails 嵌入式文档。 请帮助!!!

   $query = ['_id' => new MongoDB\BSON\ObjectID($this->id), 
            'StopsDetails' => ];

    try 
    {
        $cursor = $this->collection->find($query);
    } 
    catch (Exception $e) 
    {

    }
    return $cursor->toArray();
YourModel.findOne({_id:yourId},function(err,result){
    console.log(result); //will return all data 
    console.log(result.StopsDetails); //will retrun your stop details
}

您需要在查询的第二个参数中使用projection

$query = ['_id' => new MongoDB\BSON\ObjectID($this->id)]
$projection = ['StopsDetails' => true]

$cursor = $this->collection->find($query, $projection);

类似于 javascript 查询

db.collection.find({ '_id': ObjectId }, { 'StopDetails': 1 })

如果您想获取 MongoDB 中的特定嵌入字段,您可以使用投影

Projection

试一试mongodb playground

db.col.find({"_id" : ObjectId("5b4dd622d2ccda10c00000f0")},{"StopsDetails" : 1});