MongoDB查询数组以查找完全匹配的元素,但可能顺序不对 [英] MongoDB query an array for an exact element match, but may be out of order

查看:413
本文介绍了MongoDB查询数组以查找完全匹配的元素,但可能顺序不对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有一个文档,如下所示:

I have a document in MongoDB that looks like this:

{ users: ["2", "3", "4"] }

我正在尝试通过匹配用户数组来查询此文档.

I'm try to query this document by matching the users array.

db.things.find( { users: { $all: [ "2", "3", "4" ] } } )

该查询有效,但也会返回此文档:

That query works, but would also return this document:

{ users: ["2", "3", "4", "5"] }

最后一个要求是能够查询元素不规则的users数组,例如在查询中输入[ "3", "4", "2" ],并且能够返回列出的我的第一个文档.

Last requirement is to be able to query the users array with the elements out of order, say [ "3", "4", "2" ] in the query, and it be able to return my first document listed.

任何帮助将不胜感激.预先感谢.

Any help would be greatly appreciated. Thanks in advance.

如果有人有一个帮手,我也会用它,但是如果需要的话,我可以直接进行mongo查询.

I'm also using mongoid, if that has a helper that anyone knows about, but can do a straight mongo query if I need to.

推荐答案

您可以将查询与{users:{$ size:3}}子句合并,并调整大小以匹配要查询的用户数.这样可以确保您获得的是准确的集合,而不是子集.

You could combine your query with a { users : { $size : 3 } } clause and adjust the size to match the number of users you are querying for. That would ensure that you are getting the exact set, and not a subset.

如果元素顺序混乱,则可能需要为每个元素{{users:{$ exists:"1"}}},并将这些元素和$ size子句组合在一起.

If the elements are out of order, you might need to do a { users : { $exists : "1" } } for each, and combine those and the $size clause all together.

这篇关于MongoDB查询数组以查找完全匹配的元素,但可能顺序不对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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