简体   繁体   English

mongo在数组字段中找到var的位置

[英]mongo find where var is found in array field

I have mongo data that looks like: 我有看起来像的mongo数据:

{
    "name": "test1",
    "source": ["source1"]
},
{ 
    "name": "test2",
    "source": ["source1", "source2"]
}

I need to do a find for a document where "source1" is in the source array. 我需要查找源数组中“ source1”所在的文档。 I've tried to get $elemMatch to work as: 我试着让$ elemMatch像这样工作:

db.myCollection.find({source: {$elemMatch: {$eq:['source1']}}}) also tried db.myCollection.find({source: {$elemMatch: {$eq:{source: "source1"}}}}) db.myCollection.find({source:{$ elemMatch:{$ eq:['source1']}}}))也尝试了db.myCollection.find({source:{$ elemMatch:{$ eq:{source:“ source1 “}}}})

Neither return any documents. 都不返回任何文件。

I must be using the $elemMatch wrong, or else it may be the wrong thing to use. 我一定用错了$ elemMatch,否则使用可能是错误的事情。 How can I do a find where an array field in a document contains a specific element? 如何查找文档中的数组字段包含特定元素的位置?

Use the below syntax when you want to search for simple elements and not sub-documents. 当您要搜索简单元素而不是子文档时,请使用以下语法。

db.mycollection.find({"source":"source1"}})

This works because the elements in the array are not documents, but literals. 之所以可行,是因为数组中的元素不是文档,而是文字。 The query condition is applied on each literal. 查询条件应用于每个文字。 If a matching literal is found, that particular document is returned. 如果找到匹配的文字,则返回该特定文档。

If you do want to use $elemMatch , which is not necessary here, the syntax would be: 如果您确实想使用$ elemMatch ,则在这里不需要,语法为:

db.mycollection.find({"source":{$elemMatch:{$eq:"source1"}}})

The query that you tried: 您尝试过的查询:

db.myCollection.find({source: {$elemMatch: {$eq:{source: "source1"}}}})

would work if the source array were to have sub documents in them, such as: 如果源数组中包含子文档,则将起作用,例如:

{ 
    "name": "test2",
    "source": [{"source":"source1"}]
}

You do not need $elemMatch here. 您在这里不需要$elemMatch If your field is an array ( source: [1, ..., 4] ) and all you need is to find whether one element exist there, all you need is a simple find. 如果您的字段是一个数组( source: [1, ..., 4] ),而您所需要做的只是查找那里是否存在一个元素,那么您所要做的就是一个简单的查找。

db.mycollection.find({source: 'source1'}})

Also note that you can put an index on the field source and it will work just fine. 还要注意,您可以在字段source上放置一个索引,它会很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM