本文介绍了在find方法中使用AND-运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数组字段的集合.如果要查找所有带有特定标签的文档,请使用下一个查询:

I have a collection with the array field. If I want to find all documents with specific tag I use next query:

db.Bookmarks.find({tags : {$regex: "bbb"}})

是否可以找到所有带有2个或更多特定标签的文档?像这样:

Is it possible find all documents which 2 or more specific tags ? Something like this:

db.Bookmarks.find({tags : {$regex: "bbb"}}).find({tags : {$regex: "ccc"}})

db.Bookmarks.find({tags : {$regex: "bbb" and "ccc"}})

更新

所有文档:

> db.Bookmarks.find()
{ "Name" : "Lenta.ru", "Timestamp" : 1380912671423, "URL" : "http://www.lenta.ru", "_id" : "8vJgjH2rKAsyfHPc9", "tags" : [  "aaa",  "bbb" ] }
{ "Name" : "Яндекс", "Timestamp" : 1380912663299, "URL" : "http://www.ya.ru", "_id" : "39o2BvPHgEHkzvS4Y", "tags" : [  "aaa",  "ccc" ] }
{ "Name" : "Google", "Timestamp" : 1380912656968, "URL" : "http://www.google.com", "_id" : "MkCYfEn3WenpFvQcm", "tags" : [  "aaa",  "bbb",  "ccc" ] }

我想同时获取所有带有标签"bbb"和"ccc"的文档.

I want to get all documents with tags "bbb" and "ccc" simultaneously. Something like

db.Bookmarks.find({tags : {$regex: "bbb" and "ccc"}})

结果将是:

{ "Name" : "Google", "Timestamp" : 1380912656968, "URL" : "http://www.google.com", "_id" : "MkCYfEn3WenpFvQcm", "tags" : [  "aaa",  "bbb",  "ccc" ] }

推荐答案

您可以使用 $all 查询运算符可以做到这一点:

You can use the $all query operator to do this:

db.Bookmarks.find({tags: {$all: ['bbb', 'ccc']}})

您也可以使用正则表达式.要包含以c开头的标签,请执行以下操作:

You can use regular expressions as well. To include tags that start with c instead:

db.Bookmarks.find({tags: {$all: ['bbb', /^c/]}})

这篇关于在find方法中使用AND-运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:13
查看更多