仅查询MongoDB中包含值的文档

时间:2018-01-19 11:50:39

标签: mongodb google-maps google-maps-api-3 twitter

我想映射我从Twitter Streaming API收集的推文的坐标。虽然我是来自Twitter的收集数据,但我发现有些文件没有"坐标"。我已经在mongodb shell中完成了db.tweets.ensureIndex({"coordinates.coordinates":"2d"})以加快速度。我在PHP中的查询是db.tweets.find({},{"_id":0, "coordinates.coordinates": 1});。但是,当我重新加载我的网站时,它不会创建一个标记。如果MongoDB中的所有文档都包含坐标,我的代码似乎正在工作。但是如果有没有坐标的文件,即使有文件有坐标,我的网站也不会显示任何标记。有没有办法只投影具有"坐标"?

的文档

这是我的代码

<!DOCTYPE html>
<html>
  <head>
    <style>
       #map {
        height: 700px;
        width: 100%;
       }
    </style>
  </head>
  <body>

 <?php
  include "connection.php";

  session_start();
  ?>

 <?php

    $document = $collection->find([],['_id' => 0,'coordinates.coordinates' => 1]);
    $json = array();

    foreach($document as $row)
    {
      $json[] = $row;
    }
  ?>

<script type="text/javascript">
    var json = <?php echo json_encode($json);?>;
</script>

   <h3>My Google Maps Demo</h3>
    <div id="map"></div>

    <script>

      function initMap() 
      {
        var center = {lat: 12.8797, lng: 121.7740};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 6,
          center: center,
         // minZoom: 6
        });

          for (var i = 0, length = json.length; i < length; i++) {
          var data = json[i],
          latLng = new google.maps.LatLng(data.coordinates.coordinates[1], data.coordinates.coordinates[0]); 

          // Creating a marker and putting it on the map
          var marker = new google.maps.Marker({
             position: latLng,
            map: map,
            title: data.title
           });
        }

       }
     </script>

    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap">
     </script>

  </body>
 </html>

当我使用db.tweets.find({},{"_id":0, "coordinates.coordinates": 1});(带有和不带坐标的各种文档)在mongodb shell中查询时,这是输出:

{  }
{  }
{  }
{ "coordinates" : { "coordinates" : [ -74.0064, 40.7142 ] } }
{  }
{ "coordinates" : { "coordinates" : [ 121.9197351, 11.96795331 ] } }

有没有办法只投影这些?

{ "coordinates" : { "coordinates" : [ -74.0064, 40.7142 ] } }
{ "coordinates" : { "coordinates" : [ 121.9197351, 11.96795331 ] } }

更新

我找到了一种方法,只使用

返回具有现有值的字段

db.tweets.find( { "coordinates" : { $ne: null } }, { "_id":0, "coordinates.coordinates": 1} );

现在我试图找出如何在PHP中转换此查询。当我使用此查询$ne

时,我似乎在db.tweets.find( [ "coordinates" => [ $ne => null ] ], [ "_id"=>0, "coordinates.coordinates"=> 1] )中收到错误消息

1 个答案:

答案 0 :(得分:1)

您可以像这样使用$exists

db.tweets.find(
  {"coordinates": {$exists: true}},
  {"_id":0, "coordinates.coordinates": 1}
);