【问题标题】:Querying nested Schema in Mongodb?在 Mongodb 中查询嵌套模式?
【发布时间】:2021-01-31 09:28:03
【问题描述】:

我正在学习 MongoDB 几个星期,但我仍然不知道如何在我的项目中查询嵌套文档。我阅读了 MongoDB-docs 并在 Google 上搜索了很多,但我没有找到很好的解释或教程来解决我的问题。也许你能帮帮我!

我有三个相互引用的集合:

const shipmentSchema = new mongoose.Schema({
  item: {
    type: String,
    required: true,
  },
  cityId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "City",
  },
});

const citiesShcema = new mongoose.Schema({
  cityName: {
     type: String,
     required: true,
  },
  countryId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Countries",
    required: true,
  },
});

const countriesSchema = new mongoose.Schema({
  countryName: {
    type: String,
    required: true,
  },
});

const Shipment_new = mongoose.model("Shipment_new", shipmentSchema);
const Cities = mongoose.model("City", citiesShcema);
const Country = mongoose.model("Countries", countriesSchema);

所以,伙计们,我想知道是否有办法查询来自某个国家/地区的货物...我的意思是我想获得一个国家/地区的所有货物。所以,我试着用我自己的方法解决它,这就是我所尝试的:

const filterShipment = {
  cityId: {
    countryId: "5f6bbe558b094c14103a7776",
  },
};

const shimpents = await Shipment_new.find(filterShipment);

但这并没有奏效,所以伙计们,你们可能想在这里帮助我....我只是想获得特定国家的货物?提前致谢

【问题讨论】:

标签: javascript database mongodb mongoose


【解决方案1】:

要在 mongo 中查询多个文档(SQL 中的联接),您需要使用 $lookup。根据我从问题中了解到的情况,以下查询为您提供了countryId 的所有shipments

这里是查询。我还添加了 mongo 游乐场。这样您就可以运行查询。并根据需要进行一些更改。

db.Shipment_new.aggregate([
  {
    "$lookup": {
      "from": "City",
      "localField": "cityId",
      "foreignField": "_id",
      "as": "city"
    }
  },
  {
    "$unwind": "$city"
  },
  {
    "$match": {
      "city.countryId": 111
    }
  },
  {
    "$project": {
      item: 1,
      city: "$city.cityName",
      countryId: "$city.countryId"
    }
  }
])

这是你要找的吗?

这里是Mongo Playground

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2019-08-12
    • 2018-03-09
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多