Rohan
Rohan

Reputation: 45

formatted response for a mongo query

I saw one post where we can use query: db.collection.find({"pc.pcId": "2"}) and get a record based on pcId. result:

{
  "name" : "user",
  "number":"09xxxxxxx21",
  "pc" : [{
      "pcId" : "1",
      "pcName" : "Desktop",
      "pcOwner" : "user1"
    }, {
      "pcId" : "2",
      "pcName" : "Laptop",
      "pcOwner" : "user1"
    }
  ]}
}

My question is what if I want result like:

   {
      "pcId" : "2",
      "pcName" : "Desktop",
      "pcOwner" : "user1"
   }

Not complete record only specific piece of result for which I'm running query. any query?

Upvotes: 1

Views: 428

Answers (2)

varman
varman

Reputation: 8894

You can achieve this with aggregation. There are several ways

  1. $unwind to flat the array
  2. Match the object using $match
  3. $replaceRoot helps to replace the whole document with the object

Mongo script is given below

db.collection.aggregate([
  {
    "$unwind": "$pc"
  },
  {
    $match: {
      "pc.pcId": "2"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$pc"
    }
  }
])

Working Mongo playground


Second way

  1. Use $filter to filter the desire output
  2. Once you get the filtered result, you can get the first element of an array which is your desired output using $arrayElemAt
  3. If there is no element at 0 index, this will throw an error. To prevent it, we use $ifNull
  4. $replaceRoot helps to replace the whole document with the object

And the mongo script is

[
  {
    $project: {
      pc: {
        $ifNull: [
          {
            $arrayElemAt: [
              {
                $filter: {
                  input: "$pc",
                  cond: {
                    $eq: [
                      "$$this.pcId",
                      "1"
                    ]
                  }
                }
              },
              0
            ]
          },
          []
        ]
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$pc"
    }
  }
]

Working Mongo playground

Upvotes: 0

Mallik
Mallik

Reputation: 334

> db.version();
4.2.6
> db.users.find().pretty();
{
        "_id" : ObjectId("5f74aebe377e73757bb7cead"),
        "name" : "user",
        "number" : "09xxxxxxx21",
        "pc" : [
                {
                        "pcId" : "1",
                        "pcName" : "Desktop",
                        "pcOwner" : "user1"
                },
                {
                        "pcId" : "2",
                        "pcName" : "Laptop",
                        "pcOwner" : "user1"
                }
        ]
}
> db.users.aggregate([
... {$unwind:"$pc"},
... {$match:{"pc.pcId":"2"}},
... {$project:{
...     "_id":0,
...     "pc.pcId":1,
...     "pc.pcName":1,
...     "pc.pcOwner":1}}
... ]).pretty();
{ "pc" : { "pcId" : "2", "pcName" : "Laptop", "pcOwner" : "user1" } }
>

Upvotes: 1

Related Questions