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

Giới hạn trường và cắt mảng (slice projection) cùng lúc trong MongoDB

Sử dụng toán tử $slice trong projection. Tạo collection với document:

> db.limitAndSliceProjectionDemo.insertOne(
    {
      "_id" : 101,
      "UserName" : "Carol",
      "UserAge" : 26,
      "UserMesssage" : [
        "Hi", "Hello", "Bye", "Awesome", "Good", "Bad", "Nice", "Good Night", "Good Morning"
      ]
    }
); { "acknowledged" : true, "insertedId" : 101 }

Hiển thị document:

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

Kết quả:

{ "_id" : 101, "UserName" : "Carol", "UserAge" : 26, "UserMesssage" : [ "Hi", "Hello", "Bye", "Awesome", "Good", "Bad", "Nice", "Good Night", "Good Morning" ] }

Truy vấn giới hạn trường (loại trừ _id, UserName, UserAge) VÀ cắt mảng UserMesssage từ vị trí 2 lấy 4 phần tử:

> db.limitAndSliceProjectionDemo.find(
  { "UserName" : "Carol" },
  { "_id": 0, "UserName": 0, "UserAge": 0, "UserMesssage": { "$slice": [2, 4] } }
).pretty();

Kết quả (chỉ trả về 4 phần tử từ index 2: "Bye", "Awesome", "Good", "Bad"):

{ "UserMesssage" : [ "Bye", "Awesome", "Good", "Bad" ] }