如何使用MongoDB获取不同格式的特定数据?
为此,只需使用find()。对于其他格式,请使用pretty()。首先让我们创建一个包含文档的集合-
> db.getSpecificData.insertOne(
... {
... "StudentName": "John",
... "Information": {
... "FatherName": "Chris",
... "Place": {
... "CountryName": "US",
... "ZipCode":"111344"
... },
... "id": "1"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e039abdf5e889d7a5199509")
}
> db.getSpecificData.insertOne(
... {
... "StudentName": "Carol",
... "Information": {
... "FatherName": "Robert",
... "Place": {
... "CountryName": "UK",
... "ZipCode":"746464"
... },
... "id": "2"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e039ae6f5e889d7a519950a")
}
>
> db.getSpecificData.insertOne(
... {
... "StudentName": "David",
... "Information": {
... "FatherName": "Carol",
... "Place": {
... "CountryName": "US",
... "ZipCode":"567334"
... },
... "id": "3"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e039ae7f5e889d7a519950b")
}
>
> db.getSpecificData.insertOne(
... {
... "StudentName": "Jace",
... "Information": {
... "FatherName": "Bob",
... "Place": {
... "CountryName": "US",
... "ZipCode":"999999"
... },
... "id": "4"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e039ae8f5e889d7a519950c")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.getSpecificData.find({'Information.Place.CountryName':"US"}, {}, {limit: 2}, function(error, data) {}).pretty();这将产生以下输出-
{
"_id" : ObjectId("5e039abdf5e889d7a5199509"),
"StudentName" : "John",
"Information" : {
"FatherName" : "Chris",
"Place" : {
"CountryName" : "US",
"ZipCode" : "111344"
},
"id" : "1"
}
}
{
"_id" : ObjectId("5e039ae7f5e889d7a519950b"),
"StudentName" : "David",
"Information" : {
"FatherName" : "Carol",
"Place" : {
"CountryName" : "US",
"ZipCode" : "567334"
},
"id" : "3"
}
}
{
"_id" : ObjectId("5e039ae8f5e889d7a519950c"),
"StudentName" : "Jace",
"Information" : {
"FatherName" : "Bob",
"Place" : {
"CountryName" : "US",
"ZipCode" : "999999"
},
"id" : "4"
}
}以下是获取不同格式的特定数据的查询-
> db.getSpecificData.find({'Information.Place.CountryName':"US"}, {}).limit(2);这将产生以下输出-
{ "_id" : ObjectId("5e039abdf5e889d7a5199509"), "StudentName" : "John", "Information" : { "FatherName" : "Chris", "Place" : { "CountryName" : "US", "ZipCode" : "111344" }, "id" : "1" } }
{ "_id" : ObjectId("5e039ae7f5e889d7a519950b"), "StudentName" : "David", "Information" : { "FatherName" : "Carol", "Place" : { "CountryName" : "US", "ZipCode" : "567334" }, "id" : "3" } }热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿