下面是一个使用"保留空位置与Geonear"的示例代码:
// 导入所需的模块
const { MongoClient } = require('mongodb');
// 定义数据库连接字符串和数据库名称
const connectionString = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
// 创建一个函数来执行我们的代码
async function run() {
// 连接到数据库
const client = await MongoClient.connect(connectionString, { useUnifiedTopology: true });
const db = client.db(dbName);
// 创建一个包含地理位置数据的集合
const collection = db.collection('locations');
// 插入示例数据
await collection.insertMany([
{ name: 'Location 1', location: { type: 'Point', coordinates: [40.7128, -74.0060] } },
{ name: 'Location 2', location: { type: 'Point', coordinates: [34.0522, -118.2437] } },
{ name: 'Location 3', location: { type: 'Point', coordinates: [37.7749, -122.4194] } },
]);
// 创建一个地理位置查询
const query = {
location: {
$near: {
$geometry: {
type: 'Point',
coordinates: [34.0522, -118.2437],
},
$maxDistance: 2000, // 最大距离为2000米
},
},
};
// 执行地理位置查询并保留空位置
const result = await collection.aggregate([
{
$geoNear: {
near: {
type: 'Point',
coordinates: [34.0522, -118.2437],
},
distanceField: 'distance',
maxDistance: 2000,
spherical: true,
},
},
{
$group: {
_id: null,
locations: {
$push: {
name: '$name',
location: '$location',
distance: '$distance',
},
},
},
},
]).toArray();
// 打印结果
console.log(result[0].locations);
// 断开数据库连接
client.close();
}
// 运行代码
run().catch(console.error);
上面的代码首先连接到MongoDB数据库,然后创建一个名为"locations"的集合,并向集合中插入一些示例数据。接下来,我们定义了一个地理位置查询,该查询使用$geoNear操作符在地理位置字段上执行附近查询。我们还设置了最大距离为2000米。最后,我们使用$group操作符将查询结果分组,并将结果打印到控制台上。
请注意,此示例假设您已经安装了MongoDB驱动程序并正确设置了数据库连接信息。如果您尚未安装驱动程序,请运行以下命令进行安装:
npm install mongodb
确保将const connectionString = 'mongodb://localhost:27017';
中的连接字符串更改为适合您的实际数据库配置的值。