简体   繁体   中英

How to join two collections on a common field in mongodb?

In my database there are many issuers and many offerings. A user may create (and own) multiple issuers. I am trying to run a query that will return all offerings associated with issuers that have been created by a given user. I want the returned result to include the name of the issuer associated with the given offering (not just the ID).

Here is some abridged schema for context:

const OfferingSchema = new mongoose.Schema({
    issuerID: {
        type: String,
        required: true
    },
    offeringName: {
        type: String,
        required: true
    },
});
const Offering = mongoose.model('Offering', OfferingSchema, 'offerings');


const IssuerSchema = new mongoose.Schema({
  user_id: {
    type: String,
    required: false
  },
  name: {
    type: String,
    required: true
  },
});
const Issuer = mongoose.model("Issuer", IssuerSchema, "issuers");

From what I understand, I need to use $lookup to "join" the two collections. What I tried was this:

db.offerings.aggregate([{
    $lookup:{from: "issuers",       
            localField: "issuerID",  
            foreignField: "_id", 
            as: "issuerInfoAilias" }
}])

But I get back every offering, and each offering document has an inssuerInfoAlias field which is an empty array.

running the following query returns an offering with an issuerID of 5c953c18eb4a0a690892f001

 db.offerings.findOne({"_id" : ObjectId("5c9baa8b1fe76d79a108f3fb")})

Running the following query returns an issuer:

 db.issuers.findOne({"_id":ObjectId("5c953c18eb4a0a690892f001")})

So I know that at least one pair exists in the database.

I expect to get back all offerings with each offering including the name of the issuer that correlates to the id found in the issuerID field of the offering document. What change do I need to make in order to get that returned?

From what i can see in your schema, i think you need to use foreignField : "user_id" instead of foreignField : "_id" .

Try this:

db.offerings.aggregate([{
    $lookup:{
        from: "issuers",       
        localField: "issuerID",  
        foreignField: "user_id", 
        as: "issuerInfoAilias" 
    }
}])

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