获取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.
请显示工作查询.
推荐答案
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屋!