MongoDB query an array for an exact element match, but may be out of order

时光总嘲笑我的痴心妄想 提交于 2019-12-10 16:12:18

问题


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

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.

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.


回答1:


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.

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.




回答2:


This answer is incorrect.

to query a document for exactly matches in an array do this.

db.things.insert({a:[1,2]});

db.things.insert({a:[1,2,3]});

db.things.find({a:[1,2]});

returns {a:[1,2]}

Hope this helps - it's so obvious that it's not in the docs



来源:https://stackoverflow.com/questions/6165121/mongodb-query-an-array-for-an-exact-element-match-but-may-be-out-of-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!