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
If you want to find a document which its first pokemon’s name is "bulbasaur", try:
And if you want to return only the pokemon names, you can use projection:
See how it works on the playground example
If you want position to be dynamic and still search for "bulbasaur" you can use:
You can read more about it here =>
Query an Array of Embedded Documents
You can also test it on playground
If you want particularly that object only then use this