如何将 MongoDB 结果存储在数组中?
若想将 MongoDB 结果存储在数组中,可以使用 toArray() 方法——
var anyVariableName=db.yourCollectionName.find().toArray();
我们首先使用文档创建一个集合——
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"David Miller","CustomerAge":24,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99bd5b50a6c6dd317ad92") } > db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Sam Williams","CustomerAge":46,"isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99beab50a6c6dd317ad93") } > db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Carol Taylor","CustomerAge":23,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99bf9b50a6c6dd317ad94") }
以下查询可使用 find() 方法显示集合中的所有文档——
> db.mongoDbResultInArrayDemo.find().pretty();
这会产生以下输出——
{ "_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"), "CustomerName" : "David Miller", "CustomerAge" : 24, "isMarried" : false } { "_id" : ObjectId("5cd99beab50a6c6dd317ad93"), "CustomerName" : "Sam Williams", "CustomerAge" : 46, "isMarried" : true } { "_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"), "CustomerName" : "Carol Taylor", "CustomerAge" : 23, "isMarried" : false }
以下查询可将 MongoDB 结果存储在数组中——
> var mongoDbResultIntoArray=db.mongoDbResultInArrayDemo.find().toArray();
让我们显示上面变量中的记录——
> mongoDbResultIntoArray
这会产生以下输出——
[ { "_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"), "CustomerName" : "David Miller", "CustomerAge" : 24, "isMarried" : false }, { "_id" : ObjectId("5cd99beab50a6c6dd317ad93"), "CustomerName" : "Sam Williams", "CustomerAge" : 46, "isMarried" : true }, { "_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"), "CustomerName" : "Carol Taylor", "CustomerAge" : 23, "isMarried" : false } ]
广告