0

My Modal is :

  Data : [
            {
              Book_name : {
                  type : String,
                  unique: true,
                  required: true,
              },
              articles : [
                  {
                      article_name : {
                        type: String, 
                        index: true,
                        unique: true,
                      }
                  }
              ]
            }
     ]

I want a query like if we search article by name it will return only matched article object id.

This query which I have tried :

**MyModal.findOne({'Data.articles.article_name': {$regex: name, $options: "i"}})**

It is working fine but returning entire object .I want to return only match article name object id. Can anyone Please help me out ?

Edit :

Example data :

{
    "course_name": "Temp data",
    "content": [
        {
            "_id": {
                "$oid": "607c2d3bbb142f0008af2373"
            },
            "name": "Introduction ",
            "articles": [
                {
                    "_id": {
                        "$oid": "607c6911fe4a5e7ec5e07cdd"
                    },
                    "article_name": "What is data1?"
                },
                {
                    "_id": {
                        "$oid": "607c6a7afe4a5e7ec5e07cdf"
                    },
                    "article_name": "How data 2?"
                },
                {
                    "_id": {
                        "$oid": "607c6bc3fe4a5e7ec5e07ce1"
                    },
                    "article_name": "Why to study data3?"
                },
                {
                    "_id": {
                        "$oid": "607c6d2dfe4a5e7ec5e07ce3"
                    },
                    "article_name": "Data Types"
                },
                {
                    "_id": {
                        "$oid": "607c707dfe4a5e7ec5e08ce5"
                    },
                    "article_name": "Sample Vs data3"
                }
            ]
        }
    ]
}

If I search article name : "Why to study data3?" then It should return me this id "607c6bc3fe4a5e7ec5e07ce1".

Thanks .

Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27
  • Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – eol Jun 08 '21 at 17:08

1 Answers1

0

Try this:



//Index collection first
await db.collection('myCollection').createIndex({ "$**": "text" }, { name: "TextIndex" });

//Build query
const searchTerm = "Why to study data3";
const query = { $text: { $search: searchTerm }};
const result = await db.collection('myCollection').find(query).project({ _id: 1 }).toArray();
console.log(result._id['$oid']);

Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27