Lucifer
Lucifer

Reputation: 25

Fetch nested data from MongoDB

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"}]
    } } ] )

Upvotes: 0

Views: 60

Answers (2)

SuleymanSah
SuleymanSah

Reputation: 17858

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

Upvotes: 1

Valijon
Valijon

Reputation: 13093

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

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

MongoPlayground

Upvotes: 1

Related Questions