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

Lấy từ đầu tiên phân biệt từ chuỗi trong MongoDB

Sử dụng phương thức distinct() kết hợp map() để lấy từ đầu tiên. Tạo collection:

> db.distinctFirstWordDemo.insertOne({
  "_id": 100,
  "StudentName": "John",
  "StudentFeature": "John is a good player",
  "Subject": "MongoDB"
});
{ "acknowledged": true, "insertedId": 100 }
> db.distinctFirstWordDemo.insertOne({
  "_id": 101,
  "StudentName": "Carol",
  "StudentFeature": "Carol is not a good player",
  "Subject": "MongoDB"
});
{ "acknowledged": true, "insertedId": 101 }

Hiển thị document:

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

Kết quả:

{
  "_id": 100,
  "StudentName": "John",
  "StudentFeature": "John is a good player",
  "Subject": "MongoDB"
}
{
  "_id": 101,
  "StudentName": "Carol",
  "StudentFeature": "Carol is not a good player",
  "Subject": "MongoDB"
}

Truy vấn lấy từ đầu tiên phân biệt:

> student = db.distinctFirstWordDemo.distinct("StudentFeature", { "Subject": "MongoDB" }).map(function(st) {
  return st.split(" ")[0];
});
[ "John", "Carol" ]
> printjson(student);

Kết quả:

[ "John", "Carol" ]