4

I have already seen these posts:

String field value length in mongoDB

Select string length in mongodb

But My problem is different. When I am running this query:

db.usercollection.find({$where: "this.profile.name.length < 20"}).limit(2);

I am getting the below error:

Error: error: {
    "ok" : 0,
    "errmsg" : "TypeError: this.profile is undefined :\n_funcs2@:1:24\n",
    "code" : 139
}

when I am running this query:

db.usercollection.find({"profile.name": {$exists: true}, $where: "this.profile.name.length <20"}).limit(2); 

No error, But empty result, though my collection have 2 documents where profile.name<20

MongoDB shell version: 3.2.11

Community
  • 1
  • 1
Arijit
  • 1,633
  • 2
  • 21
  • 35
  • 1
    If you are getting the error `this.profile is undefined` why can't you then check for the field instead `db.usercollection.find({"profile": {"$exists": true}, "$where": "this.profile.name.length <20"}).limit(2);`? – chridam Jan 02 '17 at 13:23
  • how your documetns schema look? – sergiuz Jan 02 '17 at 13:28
  • @SergiuZ profile{ name = Arijit, age= 20} , address{street= abc street, zip= 2345} – Arijit Jan 02 '17 at 13:33
  • @chridam, that can throw an error also, if embedded document `profile` does not have a key `name.` – sergiuz Jan 02 '17 at 13:43
  • @Arijit, can't figure it out why your second query returns empty result, I assume is correct and there is other problem and I posted an answer. Maybe you can post more of your data ? – sergiuz Jan 02 '17 at 13:46

2 Answers2

4

There is a document where profile key (embedded document) does not exist, and javascript expression is throwing the error since is trying to access an unexisting attribute of an object:

db.usercollection.find({$where: "this.profile.name.length < 20"}).limit(2);

Your second query works OK, because it matches all documents where profile.name exists:

db.usercollection.find({"profile.name": {$exists: true}, $where: "this.profile.name.length <20"}).limit(2); 

The second query should return the desired result.

sergiuz
  • 5,353
  • 1
  • 35
  • 51
  • Thanks for the answer. First logic is true. Some of my document don't have the field. But I wonder why the second query is returning empty result. – Arijit Jan 02 '17 at 13:57
  • 1
    The second query is tested and returns the expected result on my test data. Problem might be your data? Post your documents and (check again) your query to be correct, check your flow again, I have no other clue. – sergiuz Jan 02 '17 at 14:07
-2

that profile.name can be checked in where clause itself

db.usercollection.find({$where: "this.profile && this.profile.name && this.profile.name.length < 20"}).limit(2);
Rahul Kumar
  • 2,781
  • 1
  • 21
  • 29