0

I don't quite figure out why I'm getting different results when:

> db.reference.find({"metadata.values": {address: {location: "barcelona"} } }).count();
0
> db.reference.find({"metadata.values.address.location": "barcelona"}).count();
1

Which is the difference?

The document contained into reference collection is:

{
        "_id" : "Doc1Ref2",
        "document" : "doc1",
        "metadata" : [
                {
                        "_id" : "Doc1Ref2Mdt1",
                        "user" : "user2",
                        "creationTimestamp" : ISODate("2018-09-24T12:20:56.169Z"),
                        "values" : {
                                "date" : ISODate("2018-09-24T12:20:56.171Z"),
                                "number" : 16,
                                "address" : {
                                        "street" : "Av. Diagonal",
                                        "location" : "barcelona"
                                },
                                "credentials" : [
                                        {
                                                "password" : "pwd",
                                                "login" : "main"
                                        },
                                        {
                                                "password" : "pwd",
                                                "login" : "other",
                                                "creation" : ISODate("2018-09-24T12:20:56.171Z")
                                        }
                                ],
                                "contact" : "contact name",
                                "tags" : [
                                        "tag1",
                                        "tag2"
                                ]
                        }
                }
        ],
        "timestampCreation" : ISODate("2018-09-24T12:20:56.169Z")
}
Jordi
  • 20,868
  • 39
  • 149
  • 333

1 Answers1

2

The first query matches documents where metadata.values is an exact object {address: {location: "barcelona"} }, the second is where metadata.values has an object with address.location equal to "barcelona".

The equivalent tests in javascript:

if ((document.metadata || {}).values == {address: {location: "barcelona"} }) 

and

if ((((document.metadata || {}).values || {}).address || {}).location == "barcelona") 
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
  • Is there any equivalent way to get it using first approach? I've created an index on `metadata.values` field. In fact, I'm surveying if it's possible to create an index which is able to "index" all `metadata.values.*` subfields. Could you help me about that? – Jordi Sep 26 '18 at 11:07
  • Answered [there](https://stackoverflow.com/a/52517063/1110423), but no cigar I am afraid. – Alex Blex Sep 26 '18 at 11:52