Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lấy vị trí (index) phần tử trong mảng MongoDB?

Sử dụng MapReduce với indexOf() JavaScript. Tạo collection:

> db.retrievePositionDemo.find();
{ "_id" : ObjectId("5cd569ec7924bb85b3f4893f"), "Subjects" : [ "MySQL", "MongoDB", "Java" ] }

Hiển thị document:

> db.retrievePositionDemo.find().pretty();

Kết quả:

Truy vấn MapReduce tìm vị trí của "MongoDB":

> db.retrievePositionDemo.mapReduce(
  function() {
    emit(this._id,{ "IndexValue": this.Subjects.indexOf("MongoDB") });
  },
  function() {},
  {
    "out": { "inline": 1 },
    "query": { "Subjects":"MongoDB"}
  }
);

Kết quả (vị trí index = 1):

Thử với "Java" (index = 2):

> db.retrievePositionDemo.mapReduce(
  function() {
    emit(this._id,{ "IndexValue": this.Subjects.indexOf("Java") });
  },
  function() {},
  {
    "out": { "inline": 1 },
    "query": { "Subjects":"MongoDB"}
  }
);

Kết quả: IndexValue : 2.