How can I use find in array like "tagid[0:3]==[1,2,3]" statement

I have some documents ,there are a field named “tagid” as variable size array , how can I use find the tagid like “tagid[0:3]==[1,2,3]” statement,thank you .

Welcome to the community @Chunlin_Chen !

You don’t give us a lot of information to give you an optimal answer.
Therefore, your problem may have different approaches.
Here is my contribution :+1:

You should use the $slice operator which allows to have a subset of an array. This operator, in your case, must be used within the Aggregation Framework in a $project stage. If you don’t know the Aggregation Framework, I recommend that you take M121 MongoDB University course.

So, here is my example.
I have a document in a collection with an array field that contains 5 values (strings but it doesn’t matter).

And with this aggregation pipeline you will be able to solve your problem.

                               $match: {"myArrayField.3": {$exists: true }}
                               $project: {
                                           myArrayField: 1,
                                           myNewArrayField: {$slice: ["$myArrayField", 3]}
                               $match: {"myNewArrayField": ["value1","value2","value3"]}


  1. $match: This must, must be the first stage of the pipeline.
    If you have other search criteria they must be specified here.
    In my example, I exclude all documents that have an array with less than 3 elements.
    Maybe in your case no document is in this scenario but it’s for the example :grinning:.

  2. $project: In this stage, I create a new field which contains only the first 3 elements of your array field. I also keep the original array field because I don’t know if you need all the elements of your array in your results…
    It’s the stage where you have to make your projections. The earlier, the better.

  3. $match: Here I simply do the test, an equality in your case.

You can also add a final $project to remove the new array of 3 values if you don’t need it.

It’s my solution based on the information you give us.

I hope this will help you :+1:

1 Like