0

I have a collection in the following format.

{
    "_id": "ffffc446-f33d",
    "className": "com.ezdx.vist.model.Visit",
    "organizationId": "0a0beff7-fe1e-4ab7",
    "centerId": "9aef68fe-dffd-4a7d-b0ee-f8dd3fc03303",
    "tests": [{
            "result": 157,
            "type": "PHYSICAL",
            **"name": "HEIGHT",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0

        },
        {
            "result": 8,
            "type": "RDT",
            **"name": "URIC",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0
        }

    ],
    "repeatVisit": true
}

I want the collection where test.name = "Uric" and with particular columns.

  {
    "result": 8,
    "type": "RDT",
    **"name": "Uric",**
    "consumableQuantity": 0,
    "testCost": 0,
    "testExpenseConsumable": 0
}

Somehow I manage to the desired collections but I am not able to get the desired format. Below is my query

db.visits.aggregate( [ { $unwind : "$tests" }, 
{ $match: { $and: [{"tests.name":"URIC"}]
    } } ] )

2 Answers 2

1

Try this: $replaceWith (=v4.2) or $replaceRoot (>=v3.4)

db.visits.aggregate([
  {
    $unwind: "$tests"
  },
  {
    $match: {
      "tests.name": "URIC"
    }
  },
  {
    $replaceWith: "$tests"
  }
])

MongoPlayground

Sign up to request clarification or add additional context in comments.

2 Comments

I am getting following error while using $replaceRoot "expected an object as specification for $replaceRoot stage, got string"
@Lucifer check here you need to use newRoot inside the $replaceRoot
1

As an alternative to the Valijon's answer, you can use $filter aggregation which may be faster because we didn't applied $unwind.

db.collection.aggregate([
  {
    $project: {
      items: {
        $filter: {
          input: "$tests",
          as: "item",
          cond: {
            $eq: [
              "$$item.name",
              "URIC"
            ]
          }
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $arrayElemAt: [
          "$items",
          0
        ]
      }
    }
  }
])

Playground

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.