版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1433171
目录
1. 浏览数据库
2. 插入数据
3. 查询数据
大部分摘自《MongoDB大数据处理权威指南》(第3版)。
MongoDB在第一次存储数据时会自动创建数据库和集合。要切换到已有数据库或者创建新的数据库,可使用use函数,在命令后加上数据库名,无论它是否存在:
> use library;
switched to db library
> db
library
>
通过这种方式将全局变量db设置为library。这意味着,接下来的所有输入到MongoDB shell中的命令都将在library中执行,除非将该变量重置为另一个数据库。
查看可用数据库:
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
>
在向library库存储数据前,show dbs命令不返回library库。
查看当前数据库:
> db.getName();
library
> db
library
>
查看当前数据库中的集合:
> show collections;
>
插入数据使用BSON格式。
> document = ({"Type": "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The",
... "ISBN" : "978-1-4842-1183-0", "Publisher" : "Apress",
... "Author" : ["Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim"] } );
{
"Type" : "Book",
"Title" : "Definitive Guide to MongoDB 3rd ed., The",
"ISBN" : "978-1-4842-1183-0",
"Publisher" : "Apress",
"Author" : [
"Hows, David",
"Plugge, Eelco",
"Membrey, Peter",
"Hawkins, Tim"
]
}
> db.media.insert(document);
WriteResult({ "nInserted" : 1 })
> db.media.insertOne(document);
{
"acknowledged" : true,
"insertedId" : ObjectId("5baae32864e6602b766d94c1")
}
>
insert和insertOne函数的返回值不同。insert插入单条返回WriteResult对象,插入多条返回BulkWriteResult对象。而insertOne插入单条返回文档ID,insertMany插入多条返回多个文档ID构成的数组。
> document = ( { "Type" : "Book",
... "Title" : "Definitive Guide to MongoDB 3rd ed., The",
... "ISBN" : " 978-1-4842-1183-0",
... "Publisher" : "Apress",
... "Author" : ["Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim"]
... } );
{
"Type" : "Book",
"Title" : "Definitive Guide to MongoDB 3rd ed., The",
"ISBN" : " 978-1-4842-1183-0",
"Publisher" : "Apress",
"Author" : [
"Hows, David",
"Plugge, Eelco",
"Membrey, Peter",
"Hawkins, Tim"
]
}
> db.media.insert(document);
WriteResult({ "nInserted" : 1 })
> db.media.insertOne( { "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind" });
{
"acknowledged" : true,
"insertedId" : ObjectId("5baae67464e6602b766d94c3")
}
> db.media.insertOne( { "Type" : "CD",
... "Artist" : "Nirvana",
... "Title" : "Nevermind",
... "Tracklist" : [
... {
... "Track" : "1",
... "Title" : "Smells Like Teen Spirit",
... "Length" : "5:02"
... },
... {
... "Track" : "2",
... "Title" : "In Bloom",
... "Length" : "4:15"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5baae6bb64e6602b766d94c4")
}
> db.products.insertMany( [
... { _id: 10, item: "large box", qty: 20 },
... { _id: 11, item: "small box", qty: 55 },
... { _id: 12, item: "medium box", qty: 30 }
... ] );
{ "acknowledged" : true, "insertedIds" : [ 10, 11, 12 ] }
> db.products.insertMany( [
... { item: "large box", qty: 20 },
... { item: "small box", qty: 55 },
... { item: "medium box", qty: 30 }
... ] );
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5baae89e64e6602b766d94c5"),
ObjectId("5baae89e64e6602b766d94c6"),
ObjectId("5baae89e64e6602b766d94c7")
]
}
>
在插入文档时,键名必须遵守如下规则:
查询全部数据:
db.media.find();
-- 对比SQL:
select * from media;
查询Artist = 'Nirvana'的数据:
db.media.find({ Artist : "Nirvana" });
-- 对比SQL:
select * from media where Artist = 'Nirvana';
查询Artist = 'Nirvana'的Title:
db.media.find ( {Artist : "Nirvana"}, {Title: 1} )
-- 对比SQL:
select Title from media where Artist = 'Nirvana';
查询Artist = 'Nirvana' and Type = 'CD'的Title和Tracklist:
db.media.find ( {Artist : "Nirvana", Type : "CD"}, {Title: 1, Tracklist : 1} );
-- 对比SQL:
select Title, Tracklist from media where Artist = 'Nirvana' and Type = 'CD';
(1)使用点号
嵌入式对象的元素引用:
db.media.find( { "Tracklist.Title" : "In Bloom" } )
-- 对比SQL:
select * from media where Tracklist.Title = 'In Bloom';
数组元素引用:
db.media.find( { "Author" : "Membrey, Peter" } );
-- 对比SQL:
select * from media where 'Membrey, Peter' in Author;
子对象必须精确匹配到最下一级,下面的命令不返回结果:
db.media.find( { "Tracklist" : {"Track" : "1" }} );
正确的写法为:
db.media.find( { "Tracklist.Track" : "1" } );
(2)使用sort、limit和skip
查询结果按Title正序:
db.media.find().sort( { Title: 1 });
-- 对比SQL:
select * from media order by Title asc;
返回2条记录:
db.media.find().limit( 2 );
-- 对比SQL:
select * from media limit 2;
查询结果按Title倒序返回2条:
db.media.find().sort( { Title: -1 }).limit( 2 );
-- 对比SQL:
select * from media order by Title desc limit 2;
查询结果跳过1前20条:
db.media.find().skip(20);
-- 对比SQL:
select * from media limit 21, 999999999999999;
查询结果按Title倒序,返回从21条开始的10条数据:
db.media.find().sort ( { Title : -1 } ).limit ( 10 ).skip ( 20 )
-- 对比SQL:
select * from media order by Title desc limit 20, 10;
skip和limit,当两者一起使用的时候,不管其位置顺序,默认先skip,再limit。当sort、skip、limit一起使用时,无论其位置变化,总是先sort再skip,最后limit。
db.media.find().limit(2).skip(2)的快捷写法:
db.media.find({},{}, 2, 2 );
(3)使用固定集合
固定集合具有以下性质:
创建一个固定集合,没有数据时也会在show collections中返回。
> db.createCollection("audit", {capped:true, size:20480});
{ "ok" : 1 }
> show collections;
audit
media
products
> db.audit.insertMany([{item: "large box", qty: 20},{item: "small box", qty: 55},{item: "medium box", qty: 30}]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5bab1d6c1062c31f5bdf6645"),
ObjectId("5bab1d6c1062c31f5bdf6646"),
ObjectId("5bab1d6c1062c31f5bdf6647")
]
}
>
鉴于固定集合保证了自然顺序与插入顺序一致,那么在查询数据时,就不需要再使用任何特殊的参数、任何其它特殊的命令或函数,除非希望逆转默认结果的顺序。这时将用到$natural参数。
> db.audit.find();
{ "_id" : ObjectId("5bab1d6c1062c31f5bdf6645"), "item" : "large box", "qty" : 20 }
{ "_id" : ObjectId("5bab1d6c1062c31f5bdf6646"), "item" : "small box", "qty" : 55 }
{ "_id" : ObjectId("5bab1d6c1062c31f5bdf6647"), "item" : "medium box", "qty" : 30 }
> db.audit.find().sort( { $natural: -1 } ).limit(10);
{ "_id" : ObjectId("5bab1d6c1062c31f5bdf6647"), "item" : "medium box", "qty" : 30 }
{ "_id" : ObjectId("5bab1d6c1062c31f5bdf6646"), "item" : "small box", "qty" : 55 }
{ "_id" : ObjectId("5bab1d6c1062c31f5bdf6645"), "item" : "large box", "qty" : 20 }
>
还可以使用max:参数限制添加到固定集合中的文档数量,创建集合时使用该参数。
> db.createCollection("audit100", { capped:true, size:20480, max: 100});
{ "ok" : 1 }
> db.audit100.stats()
{
"ns" : "library.audit100",
"size" : 0,
"count" : 0,
"storageSize" : 4096,
"capped" : true,
"max" : 100,
"maxSize" : 20480,
"sleepCount" : 0,
"sleepMS" : 0,
"wiredTiger" : {
...
},
"nindexes" : 1,
"totalIndexSize" : 4096,
"indexSizes" : {
"_id_" : 4096
},
"ok" : 1
}
>
(4)获取单个文档
> db.media.findOne();
{
"_id" : ObjectId("5baae32464e6602b766d94c0"),
"Type" : "Book",
"Title" : "Definitive Guide to MongoDB 3rd ed., The",
"ISBN" : "978-1-4842-1183-0",
"Publisher" : "Apress",
"Author" : [
"Hows, David",
"Plugge, Eelco",
"Membrey, Peter",
"Hawkins, Tim"
]
}
>
如果希望返回一个结果,建议使用findOne()函数。
(5)使用聚合命令
db.media.count();
-- 对比SQL:
select count(*) from media;
db.media.find( { Publisher : "Apress", Type: "Book" } ).count();
-- 对比SQL:
select count(*) from media where Publisher = 'Apress' and Type = 'Book';
count()函数默认忽略skip()或limit()函数,为确保查询不忽略这些参数,使用count(true):
> db.media.find( { Publisher: "Apress", Type: "Book" }).skip(10).count();
3
> db.media.find( { Publisher: "Apress", Type: "Book" }).skip(10).count(true);
0
>
先插入一条数据:
> document = ( { "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", ISBN:
... " 978-1-4842-1183-1", "Publisher" : "Apress", "Author" : ["Hows, David", "Membrey, Peter",
... "Plugge, Eelco", "Hawkins, Tim"] } );
{
"Type" : "Book",
"Title" : "Definitive Guide to MongoDB 3rd ed., The",
"ISBN" : " 978-1-4842-1183-1",
"Publisher" : "Apress",
"Author" : [
"Hows, David",
"Membrey, Peter",
"Plugge, Eelco",
"Hawkins, Tim"
]
}
> db.media.insert (document);
WriteResult({ "nInserted" : 1 })
>
distinct返回去重后的结果:
> db.media.distinct( "Title");
[ "Definitive Guide to MongoDB 3rd ed., The", "Nevermind" ]
> db.media.distinct ("ISBN");
[ "978-1-4842-1183-0", " 978-1-4842-1183-0", " 978-1-4842-1183-1" ]
> db.media.distinct ("Tracklist.Title");
[ "In Bloom", "Smells Like Teen Spirit" ]
>
函数group()接受3个参数:key、initial和reduce。key是分组键,initial是聚合初始值(基数),reduce定义聚合函数。
> db.media.group (
... {
... key: {Title : true},
... initial: {Total : 0},
... reduce : function (items,prev)
... {
... prev.Total += 1
... }
... }
... );
[
{
"Title" : "Definitive Guide to MongoDB 3rd ed., The",
"Total" : 4
},
{
"Title" : "Nevermind",
"Total" : 2
}
]
>
-- 对比SQL:
select Title, count(*) from media group by Title;
函数group()目前在分片环境中无法正常工作。因此在这种环境中应该使用mapreduce()。另外group()函数输出结果中的键不能超过20000个,否则将抛出异常。此类情况也可以通过mapreduce()处理。
(6)使用条件操作符
添加一些文档:
> dvd = ( { "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999,
... "Cast" : ["Keanu Reeves","Carrie-Anne Moss","Laurence Fishburne","Hugo Weaving","Gloria Foster","Joe Pantoliano"] } );
{
"Type" : "DVD",
"Title" : "Matrix, The",
"Released" : 1999,
"Cast" : [
"Keanu Reeves",
"Carrie-Anne Moss",
"Laurence Fishburne",
"Hugo Weaving",
"Gloria Foster",
"Joe Pantoliano"
]
}
> db.media.insertOne(dvd);
{
"acknowledged" : true,
"insertedId" : ObjectId("5bab30251062c31f5bdf6649")
}
> dvd = ( { "Type" : "DVD", Title : "Blade Runner", Released : 1982 } );
{ "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
> db.media.insertOne(dvd);
{
"acknowledged" : true,
"insertedId" : ObjectId("5bab303e1062c31f5bdf664a")
}
> dvd = ( { "Type" : "DVD", Title : "Toy Story 3", Released : 2010 } );
{ "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
> db.media.insertOne(dvd);
{
"acknowledged" : true,
"insertedId" : ObjectId("5bab30521062c31f5bdf664b")
}
>
> db.media.find ( { Released : {$gt : 2000} }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
-- 对比SQL:
select Type, Title, Released from media where Released > 2000;
> db.media.find ( { Released : {$gte : 1999 } }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999 }
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
-- 对比SQL:
select Type, Title, Released from media where Released >= 1999;
> db.media.find ( { Released : {$lt : 1999 } }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab303e1062c31f5bdf664a"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
>
-- 对比SQL:
select Type, Title, Released from media where Released < 1999;
> db.media.find( {Released : {$lte: 1999}}, { "Cast" : 0 });
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999 }
{ "_id" : ObjectId("5bab303e1062c31f5bdf664a"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
>
-- 对比SQL:
select Type, Title, Released from media where Released <= 1999;
> db.media.find( {Released : {$gte: 1990, $lt : 2010}}, { "Cast" : 0 });
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999 }
>
-- 对比SQL:
select Type, Title, Released from media where Released >= 1990 and Released < 2010;
> db.media.find( { Type : "Book", Author: {$ne : "Plugge, Eelco"}});
>
-- 对比SQL:
select * from media where Type = 'Book' and 'Plugge, Eelco' not in Author;
> db.media.find( {Released : {$in : [1999,2008,2009] } }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999 }
>
-- 对比SQL:
select Type, Title, Released from media where Released in (1999, 2008, 2009);
> db.media.find( {Released : {$nin : [1999,2008,2009] },Type : "DVD" }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab303e1062c31f5bdf664a"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
-- 对比SQL:
select Type, Title, Released from media where Released not in (1999, 2008, 2009);
> db.media.find ( { Released : {$in : [2010,2009] } }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
> db.media.find ( { Released : {$all : [2010,2009] } }, { "Cast" : 0 } );
>
-- 对比SQL:
select Type, Title, Released from media where Released = '2010,2009';
> db.media.find({ $or : [ { "Title" : "Toy Story 3" }, { "ISBN" : "978-1-4842-1183-0" } ] } );
{ "_id" : ObjectId("5baae32464e6602b766d94c0"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", "ISBN" : "978-1-4842-1183-0", "Publisher" : "Apress", "Author" : [ "Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim" ] }
{ "_id" : ObjectId("5baae32864e6602b766d94c1"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", "ISBN" : "978-1-4842-1183-0", "Publisher" : "Apress", "Author" : [ "Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim" ] }
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
-- 对比SQL:
select * from media where Title = 'Toy Story 3' or ISBN = '978-1-4842-1183-0';
> db.media.find({ "Type" : "DVD", $or : [ { "Title" : "Toy Story 3" },
... { "ISBN" : "978-1-4842-1183-0" } ] });
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
-- 对比SQL:
select * from media where Type = 'DVD' and (Title = 'Toy Story 3' or ISBN = '978-1-4842-1183-0');
> db.media.find({"Title" : "Matrix, The"}, {"Cast" : {$slice: 3}});
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Cast" : [ "Keanu Reeves", "Carrie-Anne Moss", "Laurence Fishburne" ] }
>
-- 对比SQL:
select Type, Title, Released, substring_index(Cast,',',3) from media where Title = 'Matrix, The';
> db.media.find({"Title" : "Matrix, The"}, {"Cast" : {$slice: -3}});
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Cast" : [ "Hugo Weaving", "Gloria Foster", "Joe Pantoliano" ] }
>
-- 对比SQL:
select Type, Title, Released, substring_index(Cast,',',-3) from media where Title = 'Matrix, The';
> db.media.find({"Title" : "Matrix, The"}, {"Cast" : {$slice: [2,3] }});
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Cast" : [ "Laurence Fishburne", "Hugo Weaving", "Gloria Foster" ] }
>
-- 对比SQL:
select Type, Title, Released,
substring_index(substring_index(@Cast,',',1-(length(Cast)-length(replace(Cast,',','')))),',',3)
from media where Title = 'Matrix, The';
> db.media.find({"Title" : "Matrix, The"}, {"Cast" : {$slice: [-5,4] }});
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Cast" : [ "Carrie-Anne Moss", "Laurence Fishburne", "Hugo Weaving", "Gloria Foster" ] }
>
-- 对比SQL:
select Type, Title, Released,
substring_index(substring_index(@Cast,',',-(length(Cast)-length(replace(Cast,',','')))),',',4)
from media where Title = 'Matrix, The';
> db.media.find ( { Released : { $mod: [2,0] } }, {"Cast" : 0 } );
{ "_id" : ObjectId("5bab303e1062c31f5bdf664a"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
-- 对比SQL:
select Type, Title, Released from media where mod(Released,2) = 0;
> db.media.find ( { Released : { $mod: [2,1] } }, { "Cast" : 0 } );
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999 }
>
-- 对比SQL:
select Type, Title, Released from media where mod(Released,2) = 1;
> db.media.find ( { Tracklist : {$size : 2} } );
{ "_id" : ObjectId("5baae6bb64e6602b766d94c4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Title" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }
>
-- 对比SQL:
select * from media where length(Tracklist)-length(replace(Tracklist,',','')) = 2;
> db.media.find ( { Author : {$exists : true } } );
{ "_id" : ObjectId("5baae32464e6602b766d94c0"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", "ISBN" : "978-1-4842-1183-0", "Publisher" : "Apress", "Author" : [ "Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim" ] }
{ "_id" : ObjectId("5baae32864e6602b766d94c1"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", "ISBN" : "978-1-4842-1183-0", "Publisher" : "Apress", "Author" : [ "Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim" ] }
{ "_id" : ObjectId("5baae64864e6602b766d94c2"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", "ISBN" : " 978-1-4842-1183-0", "Publisher" : "Apress", "Author" : [ "Hows, David", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim" ] }
{ "_id" : ObjectId("5bab22551062c31f5bdf6648"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed., The", "ISBN" : " 978-1-4842-1183-1", "Publisher" : "Apress", "Author" : [ "Hows, David", "Membrey, Peter", "Plugge, Eelco", "Hawkins, Tim" ] }
>
> db.media.find ( { Author : {$exists : false } } );
{ "_id" : ObjectId("5baae67464e6602b766d94c3"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind" }
{ "_id" : ObjectId("5baae6bb64e6602b766d94c4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Title" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Cast" : [ "Keanu Reeves", "Carrie-Anne Moss", "Laurence Fishburne", "Hugo Weaving", "Gloria Foster", "Joe Pantoliano" ] }
{ "_id" : ObjectId("5bab303e1062c31f5bdf664a"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
{ "_id" : ObjectId("5bab30521062c31f5bdf664b"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
> db.media.find ( { Tracklist: { $type : 3 } } );
{ "_id" : ObjectId("5baae6bb64e6602b766d94c4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Title" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }
>
BSON数据类型和代码如下表:
代码 | 数据类型 |
---|---|
-1 | MiniKey |
1 | Double |
2 | Character字符串(UTF8) |
3 | 嵌入式对象 |
4 | 嵌入式数组 |
5 | 二进制数据 |
7 | 对象ID |
8 | Boolean |
9 | Date |
10 | Null |
11 | 正则表达式 |
13 | JavaScript代码 |
14 | Symbol |
15 | 带作用域的JavaScript代码 |
16 | 32位整数 |
17 | 时间戳 |
18 | 64位整数 |
127 | MaxKey |
255 | MinKey |
添加一条数据:
> nirvana = ( { "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nirvana", "Tracklist" :
... [ { "Track" : "1", "Title" : "You Know You're Right", "Length" : "3:38"}, {"Track" : "5",
... "Title" : "Smells Like Teen Spirit", "Length" : "5:02" } ] } );
{
"Type" : "CD",
"Artist" : "Nirvana",
"Title" : "Nirvana",
"Tracklist" : [
{
"Track" : "1",
"Title" : "You Know You're Right",
"Length" : "3:38"
},
{
"Track" : "5",
"Title" : "Smells Like Teen Spirit",
"Length" : "5:02"
}
]
}
> db.media.insertOne(nirvana);
{
"acknowledged" : true,
"insertedId" : ObjectId("5bac38628acb19ced2e28ed4")
}
>
下面查询返回Tracklist.Title = "Smells Like Teen Spirit" or Tracklist.Track = "1"的数据:
> db.media.find ( { "Tracklist.Title" : "Smells Like Teen Spirit", "Tracklist.Track" : "1" } );
{ "_id" : ObjectId("5baae6bb64e6602b766d94c4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Title" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }
{ "_id" : ObjectId("5bac38628acb19ced2e28ed4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nirvana", "Tracklist" : [ { "Track" : "1", "Title" : "You Know You're Right", "Length" : "3:38" }, { "Track" : "5", "Title" : "Smells Like Teen Spirit", "Length" : "5:02" } ] }
>
-- 对比SQL:
select * from media where Tracklist.Title = 'Smells Like Teen Spirit' or Tracklist.Track = "1";
用$elemMatch匹配数组中的完整元素:
> db.media.find ( { Tracklist: { "$elemMatch" : { Title: "Smells Like Teen Spirit",
... Track : "1" } } } );
{ "_id" : ObjectId("5baae6bb64e6602b766d94c4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Title" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }
>
-- 对比SQL:
select * from media where Tracklist.Title = 'Smells Like Teen Spirit' and Tracklist.Track = "1";
查询集合中除了$elemMatch匹配的所有文档:
db.media.find ( { Tracklist : { $not : { "$elemMatch" : { Title: "Smells Like Teen Spirit", "Track" : "1" } } } } );
-- 对比SQL:
select * from media where not (Tracklist.Title = 'Smells Like Teen Spirit' and Tracklist.Track = "1");
可以使用JavaScript指定额外的查询表达式。这种方式的优势在于JavaScript非常灵活,并且允许执行大量的额外查询。缺点是它比MongoDB支持的原生操作符慢一点,因为它不能使用索引。下面的查询都返回同样的结果:
db.media.find ( { "Type" : "DVD", "Released" : { $lt : 1995 } } )
db.media.find ( { "Type" : "DVD", $where: "this.Released < 1995" } )
db.media.find ("this.Released < 1995")
f = function() { return this.Released < 1995 }
db.media.find(f)
(7)使用正则表达式
查询Title以'Matrix'(不区分大小写)开头的数据:
> db.media.find ( { Title : /^Matrix/ } );
{ "_id" : ObjectId("5bab30251062c31f5bdf6649"), "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Cast" : [ "Keanu Reeves", "Carrie-Anne Moss", "Laurence Fishburne", "Hugo Weaving", "Gloria Foster", "Joe Pantoliano" ] }
>
-- 对比SQL:
select * from media where Title regexp '^Matrix';
注意,不分大小写(“i”)的正则表达式查询性能不好,因为需要执行大量搜索。