Mongodb: วิธีเลือกค่าที่แตกต่างจากหลายฟิลด์


คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อเลือกค่าที่แตกต่างกันในหลายฟิลด์ใน MongoDB:

 db.collection.aggregate( 
            [
                { $group : { "_id": { field1: " $field1 ", field2: " $field2 " } } }
            ]
        )

ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้กับ ทีม คอลเลกชันที่มีเอกสารต่อไปนี้:

 db.teams.insertOne({team: " Mavs ", position: " Guard ", points: 31 })
db.teams.insertOne({team: " Mavs ", position: " Guard ", points: 22 })
db.teams.insertOne({team: " Rockets ", position: " Center ", points: 19 })
db.teams.insertOne({team: " Rockets ", position: " Forward ", points: 26 })
db.teams.insertOne({team: " Rockets ", position: " Forward ", points: 29 }) 
db.teams.insertOne({team: " Cavs ", position: " Guard ", points: 33 })

ตัวอย่าง: เลือกค่าที่แตกต่างกันในหลายช่อง

เราสามารถใช้แบบสอบถามต่อไปนี้เพื่อค้นหาค่าฟิลด์ทีมและตำแหน่งที่แตกต่างกันทั้งหมด:

 db.teams.aggregate( 
            [
                { $group : { "_id": { team: " $team ", position: " $position " } } }
            ]
        )

แบบสอบถามนี้ส่งคืนเอกสารต่อไปนี้:

 { _id: { team: 'Mavs', position: 'Guard' } }
{ _id: { team: 'Rockets', position: 'Forward' } }
{ _id: { team: 'Rockets', position: 'Center' } }
{ _id: { team: 'Cavs', position: 'Guard' } }

และเราสามารถใช้แบบสอบถามต่อไปนี้เพื่อค้นหาค่าที่แตกต่างกันทั้งหมดของช่องทีม ตำแหน่ง และคะแนน:

 db.teams.aggregate( 
        [
          { $group : {"_id": {team: " $team ", position: " $position ", points: " $points "}}}
        ]
    )

แบบสอบถามนี้ส่งคืนเอกสารต่อไปนี้:

 { _id: { team: 'Cavs', position: 'Guard', points: 33 } }
{ _id: { team: 'Rockets', position: 'Forward', points: 29 } }
{ _id: { team: 'Mavs', position: 'Guard', points: 22 } }
{ _id: { team: 'Rockets', position: 'Forward', points: 26 } }
{ _id: { team: 'Mavs', position: 'Guard', points: 31 } }
{ _id: { team: 'Rockets', position: 'Center', points: 19 } }

โปรดทราบว่าเอกสารทั้งหมดจะถูกส่งกลับเนื่องจากไม่มีเอกสารสองฉบับที่มีค่าเหมือนกันสำหรับช่องทีม ตำแหน่ง และ คะแนน

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่นๆ ใน MongoDB:

MongoDB: วิธีเพิ่มฟิลด์ใหม่ให้กับคอลเลกชัน
MongoDB: วิธีจัดกลุ่มตามและนับ
MongoDB: วิธีจัดกลุ่มตามหลายฟิลด์

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *