mongodb数组匹配 [英] mongodb array matching

查看:188
本文介绍了mongodb数组匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何完成以下任务?

db.test.save( {a: [1,2,3]} );

db.test.find( {a: [1,2,3,4]} );  //must match because it contains all required values [1, 2, 3]
db.test.find( {a: [1,2]} );  //must NOT match because the required value 3 is missing

我了解$ in和$ all,但是它们的工作方式不同.

I know about $in and $all but they work differently.

推荐答案

有趣..问题是.. $ in和$ or运算符被应用在要比较 against 集合中的每个文档,而不是文档中数组的元素..总结一下您的问题:如果集合中的任何文档恰好是子集,则您希望将其匹配传递的数组.除非您交换输入和输出,否则我想不出一种方法.我的意思是..让我们开始您的第一个输入:

db.test.find( {a: [1,2,3,4]} );

考虑将其放在一个临时集合中,temp为:

db.temp.save( {a: [1,2,3,4]} );

现在,使用$ all运算符遍历测试集合中的每个文档并临时"查找它,以确保将其完全包含,即执行以下操作:

foreach(doc in test)
{ db.temp.find( { a: { $all: doc.a } } ); }


这绝对是一种解决方法!我不确定是否缺少其他可以完成这项工作的操作员.

Interesting..The problem is..the $in and the $or operators get applied on the elements of the array that you are comparing against each document in the collection, not on the elements of the arrays in the documents..To summarize your question: You want it to be a match, if any of the documents in the collection happens to be a subset of the passed array. I can't think of a way to do this unless you swap your input and output. What I mean is..Let's take your first input:

db.test.find( {a: [1,2,3,4]} );

Consider putting this in a temporary collection say,temp as:

db.temp.save( {a: [1,2,3,4]} );

Now iterate over each document in test collection and 'find' it in temp, with the $all operator to ensure it is completely contained, i.e., do something like this:

foreach(doc in test)
{ db.temp.find( { a: { $all: doc.a } } ); }


This is definitely a workaround! I am not sure if I am missing any other operator that can do this job.

这篇关于mongodb数组匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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