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

Lấy tên tất cả các khóa (field) trong MongoDB collection

Cú pháp lấy tên tất cả khóa trong collection:

var yourVariableName1=db.yourCollectionName.findOne(); 
for(var yourVariableName2 in yourVariableName1) { 
  print(yourVariableName2); 
}

Tạo collection studentGetKeysDemo:

>db.studentGetKeysDemo.insert({"StudentId":1,"StudentName":"Larry","StudentAge":23,"StudentAddress":"US", "StudentHobby":["Cricket","Football","ReadingNovel"], "StudentMathMarks":89,"StudentDOB":ISODate('1998-04-06')});
WriteResult({ "nInserted" : 1 })

Hiển thị:

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

Lấy tên khóa:

> var allKeys=db.studentGetKeysDemo.findOne(); 
> for(var myKey in allKeys){print(myKey);}

Kết quả:

_id StudentId StudentName StudentAge StudentAddress StudentHobby StudentMathMarks StudentDOB