0

I use the following query:

Collection
    .aggregate([
    {
        $project : { follow_count: {$size: { "$ifNull": [ "$follow_users", [] ] } } }
    },
    { $lookup: {from: 'models', localField: '_id', foreignField: '_id', as: 'model'}},
])

to get this kind of JSON:

[
  {
    "_id": "1234565434567",
    "follow_count": 3,
    "model": [
      {
        "_id": "1234565434567",
        "make": "Make1",
        "name": "Model1",
        "price": 15200,
      }
    ]
  },
  {
    "_id": "123456789",
    "follow_count": 2,
    "model": [
      {
        "_id": "123456789",
        "make": "Make2",
        "name": "Model2",
        "price": 12000,
      }
    ]
  }
]

Is there a way to don't push the $lookup result inside an array to have a JSON like that? I prefer to don't use loops after the query, so I am looking for an optimized way.

[
  {
    "_id": "1234565434567",
    "follow_count": 3,
    "make": "Make1",
    "name": "Model1",
    "price": 15200,
  },
  {
    "_id": "123456789",
    "follow_count": 2,
    "make": "Make2",
    "name": "Model2",
    "price": 12000,
  }
]
1
  • Try using $unwind or $project Commented Mar 8, 2018 at 10:49

1 Answer 1

1

You can use $mergeObject operator in 3.6 version.

$mergeObject to merge the joined collection fields with other fields followed by $replaceRoot to promote the combined doc to top level.

$project with exclusion to drop the model field.

Add the following stages after $lookup

 [
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          {
            "$arrayElemAt": [
              "$model",
              0
            ]
          },
          "$$ROOT"
        ]
      }
    }
  },
  {
    "$project": {
      "model": 0
    }
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.