简体   繁体   中英

Querying nested Schema in Mongodb?

i'm learning MongoDB for a few weeks now and i have still no idea how to query nested documents in my project. I read the MongoDB-docs and googled a lot, but i found no good explanations or tutorials for my problem. Maybe you can help me!

I have three Collections which are referencing each other:

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);

So, guys I was wondering if there's way to query shipments from a country... I mean I want to get all shipments with in a country . So, I tried to work it solved with my own and this what I tried:

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

const shimpents = await Shipment_new.find(filterShipment);

But this didn't do the work so guys, you may wanna help me out here.... I just want get the shipments of a specific countray? THANKS IN ADVANCE

For querying multiple documents in mongo (Joins in SQL) you need to use $lookup . Based on what i uderstood from question, Below query gives you all the shipments by countryId .

Here is the query. I have also added mongo playground. So that you can run the query. And make some changes if needed.

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"
    }
  }
])

Is this what you are looking for?

Here is the Mongo Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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