我有两个系列:'预订'和'用户'。我想加入来自booking
和user
的数据,其中usrLastname
按升序排序。
以下是样本数据。
booking:- {"_id": ObjectId("59a00979bb4d731037000029"),
"cabinname": "xxxx",
"user": ObjectId("57877d23049ac1b819000029"),
}
user:- { "_id": ObjectId("578610de049ac1741d000029"),
"usrName": "xxxxx",
"usrFirstname": "xx",
"usrLastname": "xxxx",
}
但排序不起作用 - 它不会对asc或desc进行排序。
这是我的代码
$results = $collection->aggregate(array(
array( '$match' => array('status'=>array('$in' => array('1', '4')),'is_delete' => 0,'cabinname'=>$eachcabin['name'],'checkin_from'=> array('$lte' => new MongoDate()),'reserve_to'=>array('$gt' => new MongoDate()))),
array( '$lookup' => array(
'from' => 'user',
'localField' => 'user',
'foreignField' => '_id',
'as' => 'u'
)),
array( '$unwind' => '$u'),
array( '$sort' => array(
'u.usrLastname' => -1,
)),
));'
答案 0 :(得分:-1)
此代码适用于我:
$mongo = new \MongoClient();
$db = MASTER_DB_NAME;
$table = $this->__table;
$c = $mongo->$db->selectCollection($table);
$search_array['deletedAt'] = "";
$pipeline = array(
array(
'$match' => $search_array
),
array(
'$lookup' => array('from' => "stm_userDetails",
'localField' => "fkUserId",
'foreignField' => "_id",
'as' => "userArray",
),
),
array(
'$addFields' => array( 'userArray' =>
array('$arrayElemAt' => array(array('$filter' => array('input' => '$userArray', 'as' => 'comp', 'cond' => array('$eq' => array('$$comp.fkUserId', $UserId)))),0))),
),
array(
'$unwind' => '$userArray',
),
array(
'$sort' => array( 'addedAt' => -1 ),
),
);
$cursor = $c->aggregate($pipeline);
return $cursor;
希望这可以帮到你。 :)