1

Let say we have a collection structured like this:

{
  _id:1,
  tag:["speaker","tom"]
},
{
  _id:2,
  tag:["subject","tomatoes"]
}
{
  _id:3,
  tag:["subject","space"]
}

I can query for specific elements, such as :

db.tags.find({tag:["speaker","tom"]})

Now is it possible to perform a query with a regex matching the second element of that array ? something like :

db.tags.find({tag:["speaker",/tom.*/]}) ?

A regex on the field tag (ie : db.tags.find({tag:/sp.*/})) would match the entire array, and I'm looking for a way to make it search only on the second one... before considering to have to restructure that collection.

Update

A workaround is to use the $all operator :

db.tags.find({tag:{$all : ["speaker",/tom.*/]} })

which is equivalent to :

db.tags.find({ $and: [ { tag: "speaker }, { tags: /tom.*/ } ] }

However, that's not the correct way to do, since both element are scanned for both the string and the regex.

0

1 Answer 1

1

Allow me to redeem myself. I found you can do it this way using the aggregation framework

db.tags.aggregate([
    {$match: {"tag.1" : {$exists: 1}}},
    {$project: {one: {$slice: ["$tag", 1]}, two: {$slice: ["$tag", 1,2]}}},
    {$match: {one: "speaker", two: /tom.*/}}
])

first part make sure the array has atleast 2 elements. the project the first element onto one and the second element onto two using slice then match against the single element in each array now.

You can then either get the ID and go back to the original collection and run another query or add some more projections to this and extract the necessary data from the aggregation framework.

Sign up to request clarification or add additional context in comments.

1 Comment

Yea Sorry. I assumed since this query works db.tags.find({"tag.1": {$exists: 1}}) that you'd be able to do something similar with a find but that does not seem to be the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.