MongoDB _id 和其他字段的字段排序行为是否不同?
Is MongoDB field ordering behaviour different on _id and other fields?
我最近在我的服务器中遇到了一个错误,经过调查发现 MongoDB 字典由于 BSON 结构而被排序。
我以为我明白了,但这是一个我不明白的测试(mongo 2.6.4):字段顺序是否只对 _id
重要?
测试 1:插入 {a: 1, b: 2} 并查找 {b: 2, a: 1} -> FOUND
> db.d.insert({a: 1, b: 2})
> db.d.find()
{ "_id" : ObjectId("54c4dfd17e8b0ba11cf1539d"), "a" : 1, "b" : 2 }
> db.d.find({b: 2, a: 1})
{ "_id" : ObjectId("54c4dfd17e8b0ba11cf1539d"), "a" : 1, "b" : 2 }
测试 2:插入 {smthg: {a: 1, b: 2}} 并查找 {smthg: {b: 2, a: 1}} -> NOT FOUND
> db.d.insert({smthg: {a: 1, b: 2}})
> db.d.find({smthg: {b: 2, a: 1}})
> db.d.find({smthg: {a: 1, b: 2}})
{ "smthg" : { "a" : 1, "b" : 2 } }
感谢您的解释
我直接引用docs:
Equality matches within subdocuments select documents if the
subdocument matches exactly the specified subdocument, including the
field order.
为此,使用 dot notation:
会更好地为您服务
db.d.find({"smthg.a" : 1, "smthg.b" : 2});
我最近在我的服务器中遇到了一个错误,经过调查发现 MongoDB 字典由于 BSON 结构而被排序。
我以为我明白了,但这是一个我不明白的测试(mongo 2.6.4):字段顺序是否只对 _id
重要?
测试 1:插入 {a: 1, b: 2} 并查找 {b: 2, a: 1} -> FOUND
> db.d.insert({a: 1, b: 2})
> db.d.find()
{ "_id" : ObjectId("54c4dfd17e8b0ba11cf1539d"), "a" : 1, "b" : 2 }
> db.d.find({b: 2, a: 1})
{ "_id" : ObjectId("54c4dfd17e8b0ba11cf1539d"), "a" : 1, "b" : 2 }
测试 2:插入 {smthg: {a: 1, b: 2}} 并查找 {smthg: {b: 2, a: 1}} -> NOT FOUND
> db.d.insert({smthg: {a: 1, b: 2}})
> db.d.find({smthg: {b: 2, a: 1}})
> db.d.find({smthg: {a: 1, b: 2}})
{ "smthg" : { "a" : 1, "b" : 2 } }
感谢您的解释
我直接引用docs:
Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.
为此,使用 dot notation:
会更好地为您服务db.d.find({"smthg.a" : 1, "smthg.b" : 2});