MongoDB Find Exact Array Match 但顺序无关紧要 [英] MongoDB Find Exact Array Match but order doesn't matter

查看:45
本文介绍了MongoDB Find Exact Array Match 但顺序无关紧要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查询查找精确的数组匹配并成功检索它,但是当我尝试找出具有不同顺序值的精确数组时,它会失败.

I am querying for finding exact array match and retrieved it successfully but when I try to find out the exact array with values in different order then it get fails.

示例

db.coll.insert({"user":"harsh","hobbies":["1","2","3"]})
db.coll.insert({"user":"kaushik","hobbies":["1","2"]})
db.coll.find({"hobbies":["1","2"]})

第二个文档检索成功

db.coll.find({"hobbies":["2","1"]})

什么都不显示

请帮忙

推荐答案

当前接受的答案并不能确保准确匹配您的数组,只是大小相同并且该数组与查询数组共享至少一项.

The currently accepted answer does NOT ensure an exact match on your array, just that the size is identical and that the array shares at least one item with the query array.

例如查询

db.coll.find({ "hobbies": { "$size" : 2, "$in": [ "2", "1", "5", "hamburger" ] }  });

在这种情况下仍会返回用户 kaushik.

would still return the user kaushik in that case.

精确匹配需要做的是结合 $size$all,像这样:

What you need to do for an exact match is to combine $size with $all, like so:

db.coll.find({ "hobbies": { "$size" : 2, "$all": [ "2", "1" ] }  });

但请注意,这可能是一项非常昂贵的操作,具体取决于您的数据量和结构.由于 MongoDB 保持插入数组的顺序稳定,因此在插入到数据库时确保数组按排序顺序可能会更好,这样您在查询时就可以依赖静态顺序.

But be aware that this can be a very expensive operation, depending on your amount and structure of data. Since MongoDB keeps the order of inserted arrays stable, you might fare better with ensuring arrays to be in a sorted order when inserting to the DB, so that you may rely on a static order when querying.

这篇关于MongoDB Find Exact Array Match 但顺序无关紧要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆