查询MongoDB中的数组数组 [英] Querying an array of arrays in MongoDB

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

问题描述

说,我有一个这样的文件.

Say, I have a document like this..

"ID" : "fruit1",
"Keys" : [["apple", "carrot", "banana"]]

如何查询Keys ="carrot".以下语法均无效.

How do I query for Keys = "carrot". None of the following syntax works.

db.myColl.results.find({ "Keys" : "carrot" });
db.myColl.results.find({ "Keys" : [["carrot"]] });

以下操作虽然有效,但无济于事.

Following works though, but not helpful.

db.myColl.results.find({ "Keys" : [["apple", "carrot", "banana]]});

任何指向该查询的指针都会有所帮助.谢谢.

Any pointer to this query will be helpful. Thanks.

推荐答案

有趣的问题,这可以解决问题

Interesting question, This will do the trick

 db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})

$elemMatch用于检查数组中的元素是否与指定的匹配表达式匹配. 因此嵌套的$elemMatch将更深入嵌套数组

$elemMatch used to check if an element in an array matches the specified match expression. so nested $elemMatch will go deeper into nested arrays

测试数据

db.multiArr.insert({"ID" : "fruit1","Keys" : [["apple", "carrot", "banana"]]})
db.multiArr.insert({"ID" : "fruit2","Keys" : [["apple", "orange", "banana"]]})


db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})
{ "_id" : ObjectId("506555212aeb79b5f7374cbf"), "ID" : "fruit1", "Keys" : [ [ "apple", "carrot", "banana" ] ] }

db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['banana']}}}})

{ "_id" : ObjectId("506555212aeb79b5f7374cbf"), "ID" : "fruit1", "Keys" : [ [ "apple", "carrot", "banana" ] ] }
{ "_id" : ObjectId("5065587e2aeb79b5f7374cc0"), "ID" : "fruit2", "Keys" : [ [ "apple", "orange", "banana" ] ] }

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

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