【问题标题】:fetch data between min and max price from mongodb using node js使用节点 js 从 mongodb 获取最低和最高价格之间的数据
【发布时间】:2018-06-24 19:09:27
【问题描述】:

我正在尝试从属性模型中获取介于最低价格和最高价格之间的数据

例如,如果用户输入最低和最高价格,那么将显示该最低和最高价格之间的房产数量

我已将 $text 中的类型和标签值编入索引

我是 mongodb 的新手.. 感谢帮助。 谢谢你

这是我的控制器代码

searchProperty = async (req, res) => {
const property = await Property
// first find the property that matches
.find({
    $text: {
        $search: req.query.q
    }
}, {
    score: { $meta: 'textScore' }
})
// then sort them
.sort({
    score: { $meta: 'textScore' }
})
// limit to only 5 result
//.limit(5)
res.json(property); };

这是我的模型

const propertySchema = new mongoose.Schema({
name: {
    type: String,
    trim: true,
    required: 'Please enter your name!'
},
status: {
    type: String,
    required: 'Please enter the status!'
},
type: {
    type: String,
    required: 'Please enter your type!'
},
rooms: {
    type: String,
    required: 'Please enter your no of Rooms!'
},
old: String,
bedrooms: String,
bathrooms: String,
phone: Number,
title: {
    type: String,
    trim: true,
    required: 'Please enter your property title!'
},
price: {
    type: Number,
    required: 'Please enter your Price!'
},
area: Number,
description: {
    type: String,
    trim: true,
    required: 'Please enter your description!'
},
zipcode: Number,
slug: String,
tags: [String],
created: {
    type: Date,
    default: Date.now
},
location: {
    type: {
        type: String,
        default: 'Point'
    },
    coordinates: [{
        type: Number,
        required: 'Please enter the Coordinates!'
    }],
    address: {
        type: String,
        required: 'Please enter the Address!'
    }
},
author: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    reuqired: 'You must supply an author'
} });
   // Define our indexes
   propertySchema.index({
    type: 'text',
    tags: 'text'
  });

这是我的路线

router.get('/api/v1/search', searchProperty);

【问题讨论】:

  • 如果您想获得最小值和最大值的结果,为什么要限制结果?我建议您使用带有 $match 的聚合,包括 $text 作为第一阶段,然后在价格上再次使用带有 $gte 和 $lte 的 $match。请参阅下文 - docs.mongodb.com/manual/tutorial/text-search-in-aggregation
  • 我已经在代码中注释掉了这个限制,感谢@Avij 的提示

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

您可以为此使用$gte$lte

db.properties.find({price: { $gte: 1, $lte: 1000 } } );

这将获取价格在 1 到 1000 之间的属性。

【讨论】:

  • 天哪,这很容易.. 1 行代码.. 这就是你所需要的。谢谢你的帮助
  • @RahulGupta 如果对您有帮助,您能接受答案吗?
猜你喜欢
  • 1970-01-01
  • 2016-01-26
  • 2017-03-16
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多