MongoDb:直接查询不起作用

时间:2018-09-26 10:41:49

标签: mongodb mongodb-query

我不太清楚为什么在以下情况下会得到不同的结果

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

有什么区别?

reference集合中包含的文档为:

{
        "_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")
}

1 个答案:

答案 0 :(得分:2)

第一个查询匹配metadata.values是确切对象{address: {location: "barcelona"} }的文档,第二个查询匹配metadata.values包含address.location等于“巴塞罗那”的对象的文档。

javascript中的等效测试:

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

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