Question

My collection looks like:

{
"_id" : ObjectId("520c8976586f12c80900301d"),
"IDENTITY" : "ae4ff1546ecfe6ce6e8ebb2d870d57fb",
"NAME" : "Winmain Yao",
"TYPE" : "COMPANY",
"PUBLIC" : 1,
"BACKGROUND" : null,
"CONTACT" : {
  "PHONE" : {
    "WORK" : "18630283895",
    "HOME" : "188837283"
},
"EMAIL" : {
  "DEFAULT00001" : "zxwinmain@gmail.com"
},
"IM" : [],
"SITE" : [],
"ADDRESS" : [],
"SOCIAL" : []
},
"RELATION" : {
  "ACCOUNT" : "16713a29767fa4e8f139dfb249900c07",
  "USER" : "84a9e7a8e5f3a13d411cfa8ff4a62a50"
},
"CREATED" : 1376553334,
"UPDATED" : 0,
"DELETED" : 0
}

Now I want to get the customer who's phone = 18630283895, how can I do that?

Thanks a lot.

Was it helpful?

Solution

The following:

"PHONE" : {
    "WORK" : "18630283895",
    "HOME" : "188837283"
},

Is the wrong approach. As you invariably will have further types of phone numbers, you have ended up with a "key that is actually a value". This makes it difficult to query (and index). The better approach to this is:

"PHONE" : [
    { type: "WORK", number: "18630283895" },
    { type: "HOME", number: "188837283" },
],

Then you can very easily index it with:

db.collection.ensureIndex( { "PHONE.number": 1 } );

And query for numbers with:

db.collection.find( { "PHONE.number" : "18630283895" } );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top