Not able to fetch array list

When I insert something through the application, I am not able to fetch the array list.
{
“_id”: “a52a6341-5de0-410f-a881-42b6cfb41c29”,
“name”: “Coco”,
“animalType”: “Dog”,
“posts”: [
{
“id”: “f8d7444b-cf88-4c56-89a4-15a718321698”,
“title”: “Hello, class!”
}
]
}
I want to retrieve the posts’ id. How will I do it?
I tried several ways and it says undefined.

  1. const postsID = await aniCollection.findOne({_id: id}).subdoc;
    console.log(postsID);
  2. const posters = await aniCollection,getPostsById(postid)
    const postsID = await aniCollection(posters.posts.id);

Hi @vaishnavimecit, this might give you some insight:
https://docs.mongodb.com/manual/tutorial/query-array-of-documents/

1 Like

Hi,
I did checked the document already. But it doesn’t give me what I expected.
Thanks for the prompt response!!!

Is this for a specific lab or just a general question? I took the Python equivalent so I don’t know how the Javascript course is structured.

What it highlights is the use of $elemMatch and the dot notation, in your case posts.id.

Yes for a lab exercise in my school. we are doing it with Node & Mongo

What about something like this? It uses $[] construct specific to Nodejs.
https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html

Hi @vaishnavimecit,

Let me know if you still need help. :slight_smile:

Kanika

Hi,
Yes I still need help. I already referred. But I am not able to find. Is aggregation framework is the only way?

If I am understanding correctly, do you want to retrieve all posts through this function. I remember using it with java frameworks, but that is when there were models and functions written within it.

or do you just want a Mongo query that can retrieve all posts with a given _id ?

Kanika