我正在使用MongoDB并表达。 我有所有国家/地区的收藏,其中包含州和城市。
Picture of a part of the collection
现在, 假设我想获取所有包含“ Los”的城市(例如“ San Antonio”,“ San Diego”), 当我使用Find()时-它返回包含该州所有州和所有城市的所有文档(如上图所示),
我想返回所有文档,但只返回数组“城市”内包含该值的对象
注意::我希望获得其他国家/地区的城市名称中包含部分值的城市。
如何使用Find()根据需要返回?
她是我正在使用的架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CitiesSchema = new Schema({
capital:{
type: String,
required: true
},
currency:{
type: String,
required: true
},
emoji: {
type: String,
required: true
},
emojiU: {
type: String,
required: true
},
id: {
type: Number,
required: true
},
iso2: {
type: String,
required: true
},
iso3: {
type: String,
required: true
},
name: {
type: String,
required: true
},
native: {
type: String,
required: true
},
phone_code: {
type: String,
required: true
},
region: {
type: String,
required: true
},
states:
[{
cities:[{
id:{
type: Number,
required: true
},
latitude:{
type: String,
required: true
},
longitude:{
type: String,
required: true
},
name:{
type: String,
required: true
},
}],
id:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
state_code:{
type: String,
required: true
},
}]
,
subregion: {
type: String,
required: true
}
});
const Cities = mongoose.model('Cities',CitiesSchema);
module.exports = Cities;
编辑:我的Find()代码:
Cities.find({"states.cities.name": city})
.then((data)=>{
return res.json(data);
})
让我说我想搜索名称为“ Los Santos”的城市。我希望结果是这样的: Picture of the result I expect to be return 取而代之的是,我得到了这些国家中所有的州和城市-我不想要。
更新: 我找到了一种通过与$ unwind结合使用来返回数据的方法。
Cities.aggregate([{
$unwind: '$states'
},
{
$unwind: '$states.cities'
},
{
$match: {
'states.cities.name': {$regex: city, $options: "i"}
}
}
],
function (error, data) {
return res.json(data);
})
答案 0 :(得分:0)
尝试使用RegEx,我在MongoDB上进行搜索时会使用它。
Cities.find({"states.cities.name": new RegExp(city)})
.then((data)=>{
return res.json(data);
})
答案 1 :(得分:0)
我找到了一种通过与$ unwind一起使用聚合来返回数据的方法。
Cities.aggregate([{
$unwind: '$states'
},
{
$unwind: '$states.cities'
},
{
$match: {
'states.cities.name': {$regex: city, $options: "i"}
}
}
],
function (error, data) {
return res.json(data);
})