Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

MongoDB: ดึงคำแรกที่ไม่ซ้ำจากสตริงด้วย distinct() และ split()


สร้างคอลเลกชันตัวอย่าง

> db.demo129.insertOne({"Words":"This is the MySQL","CountryName":"US"});
{ "acknowledged": true, "insertedId": ObjectId("5e305d6368e7f832db1a7f6b") }
> db.demo129.insertOne({"Words":"MongoDB is NOSQL database","CountryName":"US"});
{ "acknowledged": true, "insertedId": ObjectId("5e305d7b68e7f832db1a7f6c") }

แสดงข้อมูล

> db.demo129.find();
{ "_id": ObjectId("5e305d6368e7f832db1a7f6b"), "Words": "This is the MySQL", "CountryName": "US" }
{ "_id": ObjectId("5e305d7b68e7f832db1a7f6c"), "Words": "MongoDB is NOSQL database", "CountryName": "US" }

คิวรี: distinct + map + split

ดึงค่า Words ที่ไม่ซ้ำ แล้วแยกคำด้วย space และเอาคำแรก:

> w = db.demo129.distinct("Words", {"CountryName": "US"}).map(function(doc){
  return doc.split(" ")[0];
});
[ "This", "MongoDB" ]

แสดงผลด้วย printjson()

> printjson(w);
[ "This", "MongoDB" ]