Search on a string array content

Hi

I have following document which has “sentence” array and I was wondering how I can search array element based on certain text (e.g . in this case word is “note”)
I have used following query but it is returning all the element of sentence instead of third element of array in this case

//query:

db.<collectionname>.find({
	_id: ObjectId("602b297f89ead6c0dd7821b8"),
	system: 'ABC',
	sentence: { $elemMatch:{ $regex:'^.*note.*' } }
})

//document :

{
	"_id" : ObjectId("602b297f89ead6c0dd7821b8"),
	"fds_language" : "EN",
	"fds_subjects" : "ERNS^ER_GEN",
	"publish_time" : ISODate("2021-02-16T01:47:03.000Z"),
	"sa_categories" : "SA_EARNINGS",
	"sentence" : [
		"Revenue $21.8M vs year-ago $41.7M",
		"Adjusted EBITDA ($1.8M) vs year-ago $2.6M",
		"Editor's note: This comment was entered 15-Feb for the record."
	],
	"story_date_time" : ISODate("2020-12-21T21:07:29.000Z"),
	"system" : "ABC"
} 

how can I change the query which allow regex based text search on element of sentence array and return only that element?

Thanks

You could use the aggregation framework with a $unwind stage to get only the specific array element.

thanks , can you provide example for it ? I am still new to mongodb.

Hi @Dhruvesh_Patel,

Here are some examples on our $unwind documentation page.

Hope this helps!
Jason

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.