在PHP MongoDB查询中使用不重复
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在PHP MongoDB查询中使用不重复,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2258字,纯文字阅读大概需要4分钟。
内容图文
![在PHP MongoDB查询中使用不重复](/upload/InfoBanner/zyjiaocheng/883/07ce16e3098e43c9aa2db530cd31eb30.jpg)
在我的cars_positions数据库和职位集合中,我有这种数据:
db.positions.find()
{ "_id" : ObjectId("536a5cd9e9df25cd8609d286"), "car" : { "type" : "sport", "ref" : "nameOfTheCar1" }, "position" : { "dateTime" : "2014-05-06T06:42:10", "latitude" : "0000.1111", "hemesphere" : "S", "longitude" : "05563.1254"}}
{ "_id" : ObjectId("536a5cd9e9df25cd8609d287"), "car" : { "type" : "sport", "ref" : "nameOfTheCar2" }, "position" : { "dateTime" : "2014-05-06T06:43:11", "latitude" : "0000.1111", "hemesphere" : "S", "longitude" : "05563.1254"}}
我试图在我的mongodb查询中使用一个独特的词.这是我当前的查询,在这里我需要迭代所有数据以创建仅具有最后位置的适当数组:
$pipeline =
[
[
'$match' =>
[
'car.ref' => ['$in' => $cars],
'position.dateTime' =>
[
'$gte' => $period['start'],
'$lte' => $period['end'],
],
],
],
[
'$sort' =>
[
'position.dateTime' => 1,
],
],
[
'$group' =>
[
'_id' => ['car.ref'],
'lastposition' => ['$last' => '$position'],
],
],
];
$command = new \MongoDB\Driver\Command($pipeline);
$cursor = $mongo->executeCommand('mybase.positions', $command);
具有原始查询的原始帖子:http://pastebin.com/BEC7nUa7
我想实现的是在car.ref上有一个不同的地方,并且只获取日期范围在$cars数组中任何汽车的最新位置.
所以我可以有一个像这样的最终数组:
array (size=1)
car1 =>
array (size=8)
'car.ref' => string 'car1' (length=7)
'dateTime' => string '2017-01-18T00:00:09' (length=19)
'latitude' => string '0000.1111' (length=9)
'hemesphere' => string 'S' (length=1)
'longitude' => string '05563.1254' (length=10)
car2 =>
car3 =>
任何想法 ?谢谢 !
解决方法:
您将需要聚合.尝试以下类似的方法.
<?php
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$cars = ['nameOfTheCar1', 'nameOfTheCar2'];
$start = new \MongoDB\BSON\UTCDateTime(strtotime('2012-05-06T06:42:10') * 1000);
$end = new \MongoDB\BSON\UTCDateTime(strtotime('2014-05-06T06:42:10') * 1000);
$pipeline =
[
[
'$match' =>
[
'car.ref' => ['$in' => $cars],
'position.dateTime' =>
[
'$gte' => $start,
'$lte' => $end,
],
],
],
[
'$sort' =>
[
'position.dateTime' => 1,
],
],
[
'$group' =>
[
'_id' => '$car.ref',
'lastposition' => ['$last' => '$position'],
],
],
];
$command = new \MongoDB\Driver\Command([
'aggregate' => 'positions',
'pipeline' => $pipeline
]);
$cursor = $mongo->executeCommand('mybase', $command);
foreach($cursor as $key => $document) {
var_dump($document);
}
?>
内容总结
以上是互联网集市为您收集整理的在PHP MongoDB查询中使用不重复全部内容,希望文章能够帮你解决在PHP MongoDB查询中使用不重复所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。