1

I have a collection of like so :

db.records.save( { name : "John Smith", addresses : [ { context : "home" , loc : [ 55.5, 42.3 ] } , { context : "work", loc : [ -74 , 44.74 ] } ] } )

And I've created an index like this:

db.records.createIndex( { "addresses.loc": "2d" } )

Now when I try and make a query like:

db.Company.findOne({ "stores.loc" : { $near :[55.5, 42.3]}})

What I expect to get is john smite with an array of addresses with only the relevant address, what I get is john smite with all of the addresses, So I do not know.

How do I solve this?

David Limkys
  • 4,907
  • 5
  • 26
  • 38
  • 1
    is there any specific reason of having all address of John in a single document ? – abhinsit Sep 17 '16 at 05:35
  • Because all of those locations are within one document, it finds the document near `[55.5, 42.3]` and returns the whole document. Maybe consider "flattening" the schema (i.e. use one document for each address). – Adam Sep 17 '16 at 05:35

1 Answers1

0

This can be fixed if you can alter your schema to take one address in a document and get nearest node from there then:

db.records.save( {
  name : "John Smith",
  address_context: "home",
  address_loc : [ 55.5, 42.3 ]
} )

db.records.save( {
  name : "John Smith",
  address_context: "work",
  address_loc : [ -74 , 44.74  ]
} )

Now create a index on address_loc and query, you will get relevant nearest nodes

abhinsit
  • 3,214
  • 4
  • 21
  • 26