[英]Querying nested Schema in Mongodb?
我已经学习 MongoDB 几个星期了,但我仍然不知道如何在我的项目中查询嵌套文档。 我阅读了 MongoDB-docs 并在谷歌上搜索了很多,但我没有找到针对我的问题的好的解释或教程。 也许你能帮帮我!
我有三个相互引用的集合:
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);
但这并没有奏效所以伙计们,你们可能想在这里帮助我.... 我只想得到特定国家的货物? 提前致谢
要在 mongo 中查询多个文档(SQL 中的连接),您需要使用$lookup
。 根据我对问题的理解,下面的查询为您提供了countryId
所有shipments
countryId
。
这是查询。 我还添加了 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"
}
}
])
这是你想要的?
这是蒙戈游乐场
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.