如何检查数组字段是否包含 MongoDB 中的唯一值或另一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5366687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an array field contains a unique value or another array in MongoDB?
提问by u443966
I am using mongodb now.
我现在正在使用 mongodb。
I have blogpost collection, and blogpost has a tags filed which is an array, e.g.
我有 blogpost 集合,并且 blogpost 有一个标签字段,它是一个数组,例如
blogpost1.tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
blogpost2.tags = ['tag2', 'tag3']
blogpost3.tags = ['tag2', 'tag3', 'tag4', 'tag5']
blogpost4.tags = ['tag1', 'tag4', 'tag5']
How can I do these searchs
我该如何进行这些搜索
- contains 'tag1'
- contains ['tag1','tag2'],
- contains any of ['tag3', 'tag4']
- 包含“标签1”
- 包含 ['tag1','tag2'],
- 包含任何 ['tag3', 'tag4']
回答by Jeff the Bear
Try this out:
试试这个:
db.blogpost.find({ 'tags' : 'tag1'}); //1
db.blogpost.find({ 'tags' : { $all : [ 'tag1', 'tag2' ] }}); //2
db.blogpost.find({ 'tags' : { $in : [ 'tag3', 'tag4' ] }}); //3
回答by heinob
My experience is that for (2) the following solution is much faster than the one with "$all":
我的经验是,对于 (2) 以下解决方案比带有“$all”的解决方案快得多:
db.blogpost.find({ $and: [ {tags: 'tag1'} ,{tags: 'tag2'} ] });
but to be honest, I do not not why. I would be interested in, if anyone knows.
但说实话,我不明白为什么。我会感兴趣,如果有人知道。