【问题标题】:Code not working properly for fetching particular embedded document代码无法正常获取特定的嵌入文档
【发布时间】:2018-05-03 11:11:02
【问题描述】:

我有一个类似 HostelTbl 的集合

 {
 "_id": ObjectId("5ae845b3d2ccda137000595d"),
 "Name": "abc",
 "Address": "gggswwrerghyjh",
 "NoOfFloors": NumberInt(4),
 "Approved": "Yes",
 "SchoolId": ObjectId("5a8e9025ff24ae113c005d42"),
 "RoomsDetails": [
  {
     "RoomId": "80a1761f-f8ee-a78f-c6ab-6f9bfbdb8ea3",
     "FloorNumber": "3",
     "RoomNumber": "5",
     "RoomType": ObjectId("5ae8267ed2ccda137000595b"),
     "NumberOfBeds": "4" 
   },
    {
     "RoomId": "56a1761f-f8ee-a78f-c6ab-6f9bfbdb8es3",
     "FloorNumber": "3",
     "RoomNumber": "4",
     "RoomType": ObjectId("5ae8267ed2ccda137000595b"),
     "NumberOfBeds": "5" 
   } 
   ] 
  }

请注意,它包含嵌入式文档 RoomsDetails。现在我只想取一个 基于 RoomId 的特定嵌入文档

我试过了

    public function fetchRoomById()
    {
    $cursor = $this->collection->aggregate(array(
    array(
    '$match' => array(
        "_id" => new MongoDB\BSON\ObjectID($this->id)),
    )
    ),
    array(
    '$project' => array(
        'RoomsDetails' => array(
            '$filter' => array(
                'input' => '$RoomsDetails',
                'as' => 'Rooms',
                'cond' => array(
                    '$eq' => array('$$Rooms.RoomId', $this->RoomId)
                )
            )
        ),
            )
         )
        );
    return $cursor->toArray();
}

它不返回匹配的嵌入文档,它返回主文档而不是嵌入文档。

请帮忙

【问题讨论】:

  • 它“完全”返回匹配的嵌入文档,当然也“内部”返回父文档。您是否只希望“仅”返回匹配的嵌入文档?为什么?因为如果这是您想要执行的那种查询,那么请将所有嵌入的文档放在另一个集合中。它们旨在“因为您想要”将父子信息嵌入在一起。
  • 不,我只想要基于 RoomId 字段的子文档...

标签: mongodb mongodb-query aggregation-framework mongodb-php php-mongodb


【解决方案1】:

我已经在本地数据库中运行了过滤器查询,它工作正常

db.users.aggregate(


[

    {
        $project: {
          "Name": 1,
         "Address": 1,
         "NoOfFloors":1,
         "Approved": 1,
         "SchoolId":1,
           items: {
                    $filter: {
                       input: "$RoomsDetails",
                       as: "item",
                       cond: { $eq: [ "$$item.RoomId", "80a1761f-f8ee-a78f-c6ab-6f9bfbdb8ea3" ] }
                    }
                 }
        }
    },
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2012-09-03
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多