猫鼬如何查询关系文件?

时间:2020-03-22 05:33:30

标签: mongodb mongoose

有两个集合。

收藏-已发布

{
    _id: "2461177814122722",
    name : "Nur"
    location: {
        type: "Point",
        coordinates: [ 90.341044,  23.787105 ]
    }
}

收藏-帖子

{
    _id: "5e7447336da7300a1cb64c51",
    model: asus,
    postedBy : "2461177814122722",
    price : 1255   
}

我该如何查询?

posts.find({
  postedBy: {
    location: {
      $near: [-74, 40],
      $maxDistance: 10
    }
  }
});

我想在下面的这份文件中进行查询。但是如何查询猫鼬中的关系文档?

{
  _id: "5e7447336da7300a1cb64c51",
  model: asus,
  postedBy: {
    name: "Nur",
    location: {
      type: "Point",
      coordinates: [90.341044, 23.787105]
    }
  },
  price: 1255
};

1 个答案:

答案 0 :(得分:2)

首先,您必须创建一个二维索引:

db.PostedBy.createIndex({ location: "2dsphere" })

然后您可以运行如下聚合:

db.PostedBy.aggregate([
   {
      $geoNear: {
         near: {
            type: "Point",
            coordinates: [-74, 40]
         },
         distanceField: "distance",
         //maxDistance: 20000, // max. Distance in Meters
         spherical: true
      }
   },
   {
      $lookup:
         {
            from: "posts",
            localField: "_id",
            foreignField: "postedBy",
            as: "posts"
         }
   },
   {
      $project: {
         model: "$posts.model",
         price: "$posts.price",
         postedBy: { name: "$name", location: "$location" }
      }
   }
])

请注意,[-74, 40][90.341044, 23.787105]超过10,000公里,请确认您的输入值。

pricemodel的值作为数组返回,因为每个“ PostedBy”可能有多个帖子。如果要获取单个元素,请追加{ $set: { model: { $arrayElemAt: ["$model", 0] } } }{ $unwind: "$model" },分别。 price

相关问题