获取MongoDB数组字段中给定元素的索引 [英] Get index of given element in array field in MongoDB
问题描述
想想这个 MongoDB 文档:
Think of this MongoDB document:
{_id:123, "food":[ "apple", "banana", "mango" ]}
问题:如何获取mango
在食物中的位置?
Question: How to get the position of mango
in food?
上面的查询应该返回2
,不要返回整个文档.
The query should return 2
in above, and don't return the whole document.
请显示工作查询.
推荐答案
从 MongoDB 3.4 版开始,我们可以使用 $indexOfArray
运算符,用于返回可以在数组中找到给定元素的索引.
Starting from MongoDB version 3.4 we can use the $indexOfArray
operator to return the index at which a given element can be found in the array.
$indexOfArray
接受三个参数.第一个是以$
符号为前缀的数组字段的名称.
$indexOfArray
takes three arguments. The first is the name of the array field prefixed with $
sign.
第二个是元素,第三个可选是开始搜索的索引.$indexOfArray
如果未指定开始搜索的索引,则返回找到该元素的第一个索引.
The second is the element and the third optional is the index to start the search at. $indexOfArray
returns the first index at which the element is found if the index to start the search at is not specified.
演示:
> db.collection.insertOne( { "_id" : 123, "food": [ "apple", "mango", "banana", "mango" ] } )
{ "acknowledged" : true, "insertedId" : 123 }
> db.collection.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$food", "mango" ] } } } ] )
{ "_id" : 123, "matchedIndex" : 1 }
> db.collection.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$food", "mango", 2 ] } } } ] )
{ "_id" : 123, "matchedIndex" : 3 }
> db.collection.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$food", "apricot" ] } } } ] )
{ "_id" : 123, "matchedIndex" : -1 }
这篇关于获取MongoDB数组字段中给定元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!