skip to Main Content

The $lookup stage will return an array of subdocuments. But the only value that I am interested in from the result of the $lookup is the the _id value. So instead of an array of { _id: ObjectId() }, how do I flatten this array into just an array of ObjectId: [ ObjectId(), Objectid(), ... ]

2

Answers


  1. db={
      "orders": [
        {
          key: 1,
          
        },
        {
          key: 2,
          
        },
        {
          key: 3,
          
        }
      ],
      "inventory": [
        {
          id: 1,
          name: "a"
        },
        {
          id: 2,
          name: "b"
        },
        {
          id: 3,
          name: "c"
        },
        {
          id: 4,
          name: "d"
        }
      ]
    }
    

    Aggregation :

    db.orders.aggregate([
      {
        "$lookup": {
          "from": "inventory",
          "localField": "key",
          "foreignField": "id",
          "as": "result"
        }
      },
      {
        "$project": {
          _id: 0,
          result: 1
        }
      },
      {
        "$unwind": "$result"
      },
      {
        "$group": {
          "_id": null,
          "result": {
            "$push": "$result.id"
          }
        }
      }
    ])
    

    Output : returns ID in array (we can have mongodb objectId) but i have used simple numeric ID

    [
      {
        "_id": null,
        "result": [
          1,
          2,
          3
        ]
      }
    ]
    
    Login or Signup to reply.
  2. You can simply map the array of subdocuments, using $map, like this:

    db.orders.aggregate([
      {
        "$lookup": {
          "from": "inventory",
          "localField": "key",
          "foreignField": "id",
          "as": "result"
        }
      },
      {
        "$addFields": {
          "result": {
            "$map": {
              "input": "$result",
              "as": "item",
              "in": "$$item._id"
            }
          }
        }
      }
    ])
    

    Playground link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search