MongoDB 查询数组以获取精确的元素匹配,但可能是无序的
我在 MongoDB 中有一个如下所示的文档:
{ users: ["2", "3", "4"] }
我尝试通过匹配 users 数组来查询该文档。
db.things.find( { users: { $all: [ "2", "3", "4" ] } } )
该查询有效,但也会返回此文档:
{ users: ["2", "3", "4", "5"] }
最后一个要求是能够查询元素不按顺序排列的 users 数组,例如 [ "3", "4", "2" ]
在查询中,它能够返回我列出的第一个文档。
任何帮助将不胜感激。提前致谢。
我也在使用 mongoid,如果它有一个任何人都知道的助手,但如果需要的话可以直接进行 mongo 查询。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将查询与 { users : { $size : 3 } } 子句结合起来,并调整大小以匹配您要查询的用户数量。这将确保您获得精确的集合,而不是子集。
如果元素无序,您可能需要为每个元素执行 { users : { $exists : "1" } } ,并将它们和 $size 子句组合在一起。
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.
这个答案是不正确的。
要查询文档以获取数组中的完全匹配项,请执行以下操作。
db.things.insert({a:[1,2]});
db.things.insert({a:[1,2,3]});
db.things.find({a:[1,2]});
returns {a:[1,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