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