MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Den Index eines Elements in einem MongoDB-Array-Feld finden

Mit MongoDB 3.4 kannst du den Operator $indexOfArray verwenden, um die Position eines bestimmten Elements innerhalb eines Arrays zurückzugeben.

$indexOfArray nimmt drei Argumente. Das erste ist der Array-Feldname mit vorangestelltem $. Das zweite ist das zu suchende Element, und das dritte, optionale Argument ist der Index, ab dem gesucht werden soll. Wird kein Startindex angegeben, wird die erste passende Position zurückgegeben.

Demo:

> 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 }