คุณสามารถใช้แนวคิดของการลดแผนที่เพื่อรับตำแหน่งในอาร์เรย์ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.retrievePositionDemo.find();
{ "_id" : ObjectId("5cd569ec7924bb85b3f4893f"), "Subjects" : [ "MySQL", "MongoDB", "Java" ] } ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.retrievePositionDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
"Subjects" : [
"MySQL",
"MongoDB",
"Java"
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อดึงตำแหน่งในอาร์เรย์ใน MongoDB -
> db.retrievePositionDemo.mapReduce(
... function() {
... emit(this._id,{ "IndexValue": this.Subjects.indexOf("MongoDB") });
... },
... function() {},
... {
... "out": { "inline": 1 },
... "query": { "Subjects":"MongoDB"}
... }
... ); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"results" : [
{
"_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
"value" : {
"IndexValue" : 1
}
}
],
"timeMillis" : 662,
"counts" : {
"input" : 1,
"emit" : 1,
"reduce" : 0,
"output" : 1
},
"ok" : 1
} ดูตัวอย่างผลลัพธ์ด้านบน ดัชนีหรือตำแหน่งของค่า MongoDB คือ 1 คุณสามารถตรวจสอบค่า “Java” ซึ่งอยู่ที่ตำแหน่ง 2 -
> db.retrievePositionDemo.mapReduce(
... function() {
... emit(this._id,{ "IndexValue": this.Subjects.indexOf("Java") });
... },
... function() {},
... {
... "out": { "inline": 1 },
... "query": { "Subjects":"MongoDB"}
... }
... ); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"results" : [
{
"_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
"value" : {
"IndexValue" : 2
}
}
],
"timeMillis" : 30,
"counts" : {
"input" : 1,
"emit" : 1,
"reduce" : 0,
"output" : 1
},
"ok" : 1
}