• Scene:

    There are two collections as follows:

    company: {_id: ObjectId("..." ), countryId: "566eb3c704c7b31facbb0007"} country: { _id: ObjectId("566eb3c704c7b31facbb0007"), name:"..." }Copy the code

    Normal association:

    { $lookup: {
           from: "country".localField: "countryId",    <= string
           foreignField: "_id",    <= ObjectId
           as: "country"
    }}
    Copy the code

    But it turned out to be ineffective

  • Solution:

    1. Using the $project

      db.company.aggregate([
        {
          "$project": {
            "countryId": {
              "$toObjectId": "$countryId"}}}, {"$lookup": {
            "from": "country"."localField": "countryId"."foreignField": "_id"."as": "country"}}])Copy the code

      Or:

      db.company.aggregate([
        {
          "$project": {
            "_id": {
              "$toString": "$_id"}}}, {"$lookup": {
            "from": "country"."localField": "countryId"."foreignField": "_id"."as": "country"}}])Copy the code
    2. Use the let property of $lookup

      db.company.aggregate([
        { 
            "$lookup": {
                "let": { "countryId": { "$toObjectId": "$countryId"}},"from": "country"."pipeline": [{"$match": { "$expr": { "$eq": [ "$_id"."? countryId"]}}}],"as": "country"}}])Copy the code
    3. Using the $addFields

      db.role.aggregate([
        { "$addFields": { "countryId": { "$toObjectId": "$countryId" }}},
        { "$lookup": {
          "from": "country"."localField": "countryId"."foreignField": "_id"."as": "country"}}])Copy the code