2

I have a Mongo db structure that looks like this and I would like to retrieve all the entries where blood type length is bigger than 2.

{
    "_id" : ObjectId("5dba8987b4a39c13bc104a23"),
    "contact" : {
        "firstName" : "Mark",
        "lastName" : "Doe",
        "parentsBloodType" : [ 
            {
                "type" : "AB+",
            }, 
            {
                "type" : "A+",
            }, 
        ],
    },
    "createdAt" : ISODate("2019-10-31T07:13:11.278Z"),
    "updatedAt" : ISODate("2019-11-26T09:59:41.611Z")
}

{
    "_id" : ObjectId("5dba898fdsw54c132c104a23"),
    "contact" : {
        "firstName" : "Helen",
        "lastName" : "Fly",
        "parentsBloodType" : [ 
            {
                "type" : "O-",
            }, 
            {
                "type" : "AB-",
            }, 
        ],
    },
    "createdAt" : ISODate("2019-10-31T08:13:11.278Z"),
    "updatedAt" : ISODate("2019-11-26T09:59:41.611Z")
}

I tried the following query:

db.users.find({"contact.parentsBloodType.type" : {$exists:true}, "$expr": { "$gt": [ { "$strLenCP": "$contact.parentsBloodType.type" }, 2 ] } })

But I got this error:

Error: error: {
    "ok" : 0,
    "errmsg" : "$strLenCP requires a string argument, found: array",
    "code" : 34471,
    "codeName" : "Location34471"
}

How can I correctly do this?

2
  • 1
    Do you want the whole document in the output or just the array elements that match the "contact.parentsBloodType.type"'s length>2? Commented Dec 13, 2019 at 8:54
  • I want the whole document Commented Dec 13, 2019 at 9:01

1 Answer 1

5

This query will match documents where the type field length is 3 or greater:

db.users.find( { "contact.parentsBloodType.type" : { $exists: true }, "contact.parentsBloodType.type": { $regex: /.{3,}/ } } )


NOTES: The regular expression .{3,} means any character (specified by dot (.) metacharacter) with length of 3 or greater (specified by {3,}). Also, see MongoDB's $regex query operator.

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

2 Comments

Does this query works if contact.parentsBloodType is an array of 2 [{type: "a"}, {type: "abc"}]? Wouldn't the document be returned?
It works, because the "abc" has a string length of 3 (which is greater than 2).

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.