Shuo
Shuo I'm a DBA(Database Administrator), we can share and discuss MySQL, MongoDB, Redis and other databases here, also including learning Python, Shell, Golang together.

Tips:MongoDB中的embedded document(嵌套文档)查询注意事项

Tips:MongoDB中的embedded document(嵌套文档)查询注意事项

背景

最近在查询MongoDB中的数据时,发现查询不到数据,查询语句为:db.person.find({“name”:{
last: “Matsumoto”,
first: “Yukihiro”
}})
数据库中数据为:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "_id" : <value>,
    "name" : { "first" : <string>, "last" : <string> },       // embedded document
    "birth" : <ISODate>,
    "death" : <ISODate>,
    "contribs" : [ <string>, ... ],                           // Array of Strings
    "awards" : [
        { "award" : <string>, year: <number>, by: <string> }  // Array of embedded documents
        ...
    ]
}

问题定位

交换“name”中的属性顺序,发现必须与数据库中的一致,才能查询到数据~

官方文档


The name field must match the embedded document exactly.

果然,在查询嵌套的文档时候,字段顺序需要与存储时候的保持一致,否则会查询不到数据。
https://docs.mongodb.com/manual/reference/method/db.collection.find/

comments powered by Disqus