skip to Main Content

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

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

3

Answers


  1. 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

    Login or Signup to reply.
  2. If you want position to be dynamic and still search for "bulbasaur" you can use:

    db.collection.find({
      "pokemon": {
        "$elemMatch": {
          name: "bulbasaur"
        }
      }
    })
    

    You can read more about it here =>
    Query an Array of Embedded Documents

    You can also test it on playground

    Login or Signup to reply.
  3. If you want particularly that object only then use this

    db.collection.find({
      "pokemon.name": "Bulbasaur"
    },
    {
      "pokemon.$": 1
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search