MongoDB中查找精确匹配阵列,但顺序并不重要 [英] MongoDB Find Exact Array Match but order doesn't matter

查看:195
本文介绍了MongoDB中查找精确匹配阵列,但顺序并不重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查询寻找精确匹配阵列,并成功取回,但是当我试图找出在不同的顺序值的精确数组那么它得到失败。

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" ] }  });

仍然会返回用户考希克在这种情况下。

would still return the user kaushik in that case.

您需要的精确匹配做的是结合 $大小 $所有 ,像这样:

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中查找精确匹配阵列,但顺序并不重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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