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
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.
db.yourCollection.aggregate([{
$match: {"myArrayField.3": {$exists: true }}
},
{
$project: {
myArrayField: 1,
myNewArrayField: {$slice: ["$myArrayField", 3]}
}
},
{
$match: {"myNewArrayField": ["value1","value2","value3"]}
}])
Stages
-
$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 . -
$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. -
$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