简体   繁体   English

如何过滤MongoDB集合文档的数组

[英]How to filter MongoDB collection document's array

I am new in MongoDB and need a help. 我是MongoDB的新手,需要帮助。 In my DB I am trying to create a collection, which has only one document.T hat document has a simple key ` cities, which is an array of 124247 objects. 在我的数据库中,我试图创建一个仅包含一个文档的集合。该文档具有一个简单的关键字`city,该数组包含124247个对象。 Here is my code 这是我的代码

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const cities = require('cities.json');
const Schema = mongoose.Schema;
const db = mongoose.connection;
const app = express();

mongoose.connect("mongodb://localhost:27017/cities");

db.once("open", function() {
  console.log("Connection ok.");
})

const cityScheme = new Schema({
  cities: Array
});

const WorldCities = mongoose.model("WorldCities", cityScheme);
const myCities = new WorldCities({
  cities: cities
}).save().then(data => console.log({}.toString.call(data.cities), 'dataaa'));

WorldCities.find({
  name: "Yerevan"
}, function(err, data) {
  console.log(data, 'Armenia');
});
cityScheme.statics.getSearchedcity = function(res) {
  this.find({}, (err, citysList) => res.json({
    citysList
  }));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/api/city', (req, res) => {

})

app.listen(3000);

This is the link to cities.json ` Cities.json . 这是cities.json`链接Cities.json

So here I want to find the city with name Yerevan, but I don't know how to find it. 因此,我想在这里找到名称为埃里温的城市,但我不知道如何找到它。

You are using mongoose and from the look of your raw data it seems you are looking for only one document ... also it seems your schema is defined so that you have the cities property which contains the cities objects from your JSON so: 您正在使用mongoose和原始数据的外观看起来你正在寻找只有一个文档......也似乎你的架构定义,让你拥有cities它包含了城市从您的JSON对象等等属性:

WorldCities.findOne({
  'cities.name': "Yerevan"
}, function(err, model) {
  // do something with the model here
  console.log(model);
});

findOne will locate only one document for you and return it in the callback. findOne只会为您找到一个文档,并在回调中返回它。

See if this will get you the record. 看看是否能为您取得记录。

Use .filter 使用.filter

Ex: 例如:

arrayOfCiteis.filter(myC => myC.name === "Yerevan")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM