Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to project a list of a specific field from a nested list of objects?

I have mongodb documents, each contains a pokemon array, where each item is an object. This is a sample document:

{
  _id: ObjectId("60a8f82df06d8601849b2a01")
  pokemon: [
    {
      "id": 1,
      "num": 1,
      "name": "bulbasaur",
      "img": "img.com",
      "type": ["grass", "poison"],
      "height": 112,
      "weight": 33
    },
    {
     
      "id": 2,
      "num": 2,
      "name": "char",
      "img": "img.com",
      "type": ["grass", "poison"],
      "height": 112,
      "weight": 33
    }
  ]
}

I want to extract the names from this list.

This is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const client = new MongoClient(url);
console.log("connected")
await client.connect();
const db = client.db('cluster0');
const collection = db.collection('testing');

let datas = await collection.find({
    'pokemon.0': {
        name: "bulbasaur"
    }
}).toArray();
console.log(datas)

Tried different query operators such as text matching but still not working

>Solution :

If you want to find a document which its first pokemon’s name is "bulbasaur", try:

let data = await collection.find({"pokemon.0.name": "bulbasaur"})

And if you want to return only the pokemon names, you can use projection:

let data = await collection.findOne(
  {"pokemon.0.name": "bulbasaur"},
  {_id: 0, names: {$map: {input: "$pokemon", in: "$$this.name"}}}
)
console.log(data.names)

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading