1

I have the following document with this array:

"r" : [{
    "id" : "890",
    "ca" : "Other CPF Schemes and Priorities",
    "su" : "National Day Rally 2015"
  }, {
    "id" : "1031-52347",
    "ca" : "Current Events",
    "su" : "Lee Kuan Yew"
  }]

and I would like to list all documents where the id has got a dash so document with "id" : "1031-52347" will be returned.

I tried this:

{
 r: { id: { $in: [/^-/] } }
}

but not able to get anything.

What would be the correct syntax?

1 Answer 1

1

I used this regex:

^[0-9]+-[0-9]+$

Regular expression visualization

Debuggex Demo

You should try this database query:

"r":
{    
    { "id": {"$regex" : new RegExp("^[0-9]+-[0-9]+$") } }
}    

UPDATE

Working database queries by Blakes Seven

db.mydb.find({ "r.id": { "$regex": "^[0-9]+-[0-9]+$" }}) 

or

db.mydb.find({ "r.id": /^[0-9]+-[0-9]+$/ })
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Laszlo I am using db.mydb.find(), how do I put the query above? It gave me "Cannot deserialize BsonDocument from BsonType String."
@StevenYong The regex principle is correct but the query syntax is wrong. It should be : db.mydb.find({ "r.id": { "$regex": "^[0-9]+-[0-9]+$" }}) or db.mydb.find({ "r.id": /^[0-9]+-[0-9]+$/ }) depending on what makes sense to you. It is also the "dot notation" used here that is just as important as the regular expression. Without it, you are looking for an "object" with an "exact match", which means both an object and not an array and also one that "only" contains the field id. And of course that does not exist.
Awesome @BlakesSeven, that helps a lot, especially the dot notation info.

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.