从集合文档中筛选出字段并将其存储在新集合中

时间:2016-08-25 09:35:50

标签: mongodb mongodb-query

我有以下收集文件

 {

            "Dine" : {
                    "Cuisine" : "North Indian",
                    "Popular Dishes" : "Aaloo Tikki, Pao Bhaji, Bhalla Papdi",
                    "Dine In Available" : "Yes",
                    "Online Booking" : "",
                    "Home Delivery" : "",
                    "Pure Veg" : "Yes",
                    "Restaurant Type" : "",
                    "Air Conditioned" : "",
                    "Outdoor Area" : "",
                    "Pint of Beer" : "",
                    "Bar Available" : "",
                    "Wifi" : "",
                    "Number of Deals" : "",
                    "Happy Hours" : "",
                    "Cost for 2" : "Rs 0-250",
                    "Credit Cards Accepted" : "",
                    "Deal Available" : ""
            },
            "Location Details" : {


                    "Latitude" : "28.7004740",
                    "Longitude" : "77.1174010",

            },
            "MetaData" : {
                    "Meta Description" : "",
                    "Meta Keywords" : ""
            },
            "Operation Hours" : {
                    "Operation Hours" : "11 AM-11 PM"
            },
            "Other Options" : {
                    "Chain Name" : "",
                    "Expiry Date" : "",
                    "As seen in" : "",
                    "Deals Head" : "",
                    "Deals ID" : "",
                    "Events Head" : "",
                    "Events ID" : "",
                    "Show Bookings" : "",
                    "Form Reciever Email" : "",
                    "Powered By" : "",
                    "Show Photos" : ""
            },
            "__v" : 0,
            "_id" : "-bittoo"
    }

我想制作一份文件:

  {
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [125.6, 10.1]
  }
}

默认情况下写入类型: Feature geometry.type: Point。此外,坐标是“位置”的纬度和经度细节“,我想进一步存储这些生成的结果以存储在另一个集合中。

1 个答案:

答案 0 :(得分:0)

以下查询和javascript功能将帮助您按照您的期望创建新文档。

在mongo shell中执行查询

db.yourcollectionname.find().forEach(function(doc){
   var array = [doc.LocationDetails.Latitude, doc.LocationDetails.Longitude];
   var geometry = { "type" : "point",  "coordinates" : array};
   var newDoc = {};
   newDoc["type"] = "Feature";
   newDoc["geometry"] = geometry;

   db.yournewcollectionname.insert(newDoc);
});

执行上述查询后,您可以执行查找

db.yournewcollectionname.find()并在新馆藏中查看所需的文件。

示例输出

{
        "_id" : ObjectId("57bee0cbc9735bf0b80c23e0"),
        "type" : "Feature",
        "geometry" : {
                "type" : "point",
                "coordinates" : [
                        "28.7004740",
                        "77.1174010"
                ]
        }
}

注意:我删除了"Location Details"中的空格,并将其作为"LocationDetails"来获取查询。没有空格处理关键名称会更容易,这也是一种很好的做法。

另一种方法是我们可以同时使用$aggregate$out来获得相同的结果。

请参阅此帖以获取更多信息Save Subset of MongoDB Collection to Another Collection

希望它有帮助!