微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MongoDB ::为什么嵌入式文档索引不会以相反的顺序返回文档?

如何解决MongoDB ::为什么嵌入式文档索引不会以相反的顺序返回文档?

| 这来自MongoDB文档:
db.factories.insert( { name: \"xyz\",metro: { city: \"New York\",state: \"NY\" } } );
db.factories.ensureIndex( { metro : 1 } );
// this query can use the above index:
db.factories.find( { metro: { city: \"New York\",state: \"NY\" } } );
//As well as this
db.factories.find( { metro: { $gte : { city: \"New York\" } } } );

// But this query will not return the document because the order of the fields is significant and doesn\'t match in this case
db.factories.find( { metro: { state: \"NY\",city: \"New York\" } } );
为什么文件顺序很重要?     

解决方法

        因为在JSON和BSON中,字段的顺序在序列化时会有所不同。即
{ city: \"New York\",state: \"NY\" }
与...不同
{ state: \"NY\",city: \"New York\" }
在第一种情况下,实际索引的值将为\“ New YorkNY \”,在第二种情况下(大约)为\“ NYNew York \”。由于没有方案,因此无法在搜索索引中的嵌入式文档之前标准化字段顺序。 为了克服这个问题,您可以使用复合索引:
db.factories.ensureIndex( { \"metro.city\": 1,\"metro.state\": 1 })
并使用查询(这里的顺序无关紧要):
db.factories.find( { \"metro.city\": \"New York\",\"metro.state\": \"NY\" } )
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。