mongodb command

1. Common database commands
1. Help to view command prompts


Copy code as follows:

help
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help()

; 、Switch/create database

Copy the code as follows:

use yourDB; When creating a collection (table), the current database will be created automatically

3. Query all databases

Copy code as follows:

show dbs;

4. Delete the currently used database

Copy code as follows :

db.dropDatabase();

5. Clone the database from the specified host

Copy code as follows:

db.cloneDatabase("127.0.0.1"); Clone the data of the database on the specified machine to the current database

6. From the specified machine Copy the data of the specified database to a database The

copy code code is as follows:

db.copyDatabase("mydb", "temp", "127.0.0.1"); Copy the data of the local mydb to the temp database

7. Repair the current database

Copy The code code is as follows:

db.repairDatabase();

8. View the currently used database

The copy code is as follows:

db.getName();
db; The db and getName methods have the same effect, both can query the currently used database

9. Display the current db status

Copy code as follows:

db.stats();

10. Current db Version The

copy code is as follows:

db.version();

11. View the link machine address of the current db. The

copy code is as follows:

db.getMongo();


2. Collection
1. Create a collection (table)


Copy the code as follows :

db.createCollection("collName", {size: 20, capped: 5, max: 100});//If the creation is successful, it will display {"ok":1}
//Determine whether the collection is a fixed capacity db.collName.isCapped ();

2. Get the aggregated collection (table) of the specified name. The

copy code is as follows:

db.getCollection("account");

3. Get all the aggregated collections of the current db. The

copy code is as follows:

db.getCollectionNames();

4. Display the status of all clustered indexes in the current db. The

copy code code is as follows:

db.printCollectionStats();

3. User related
1. Add a user

Copy the code as follows:

db.addUser("name");
db.addUser("userName", "pwd123", true); Add user, set password, Whether read-only

2. Database authentication, security mode

Copy code as follows:

db.auth("userName", "123123");

3. Display all current users

Copy code as follows:

show users;

4. Delete user

Copy code as follows :

db.removeUser("userName"); 4. Aggregate

collection query 1.
Query all records If it cannot be displayed, you can use the it iterative command to query the next page of data. Note: Type it command without ";" but you can set the size of data displayed on each page, use DBQuery.shellBatchSize= 50; so that 50 records will be displayed on each page. 2. Query the duplicate data of a column in the current aggregated set after the query is removed. Copy code as follows:












db.userInfo.distinct("name");
will filter out the same data in name,
equivalent to : select distict name from userInfo;

3. Query records with age = 22

Copy code as follows:

db.userInfo.find({"age ": 22});
Equivalent to: select * from userInfo where age = 22;

4. Query records with age > 22

Copy code as follows:

db.userInfo.find({age: {$gt: 22}});
Equivalent In: select * from userInfo where age >22;

5. Query records with age < 22

Copy code as follows:

db.userInfo.find({age: {$lt: 22}});
Equivalent to: select * from userInfo where age <22;

6. Query records with age >= 25

Copy code as follows:

db.userInfo.find({age: {$gte: 25}});
Equivalent to: select * from userInfo where age >= 25;

7 , query records with age <= 25

Copy code is as follows:

db.userInfo.find({age: {$lte: 25}});

8. Query age >= 23 and age <= 26

Copy the code as follows:

db.userInfo.find({age: {$gte: 23, $lte: 26}});

9. Query the data containing mongo in the name

Copy code as follows:

db.userInfo.find({name: /mongo/});
//equivalent to %%
select * from userInfo where name like '%mongo%';

10.

Copy as follows:

db.userInfo.find({name: /^mongo/});
select * from userInfo where name like 'mongo%';

11. Query the data of the specified column name and age

Copy code as follows:

db.userInfo.find({}, {name: 1, age: 1});
Equivalent to: select name, age from userInfo; of

course, the name can also be true or false , When using ture, the effect of name: 1 is the same. If false is used, name is excluded, and column information other than name is displayed.
12. Query the specified column name, age data, age > 25

The code to copy the code is as follows:

db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
Equivalent to: select name, age from userInfo where age >25;

13. According to Age sort

Copy the code as follows:

Ascending: db.userInfo.find().sort({age: 1});
Descending: db.userInfo.find().sort({age: -1});

14. Query name = zhangsan, age = 22 data

Copy code is as follows:

db.userInfo.find({name: 'zhangsan', age: 22});
Equivalent to: select * from userInfo where name = 'zhangsan' and age = '22 ';

15. Query the first 5 pieces of data,

copy code as follows:

db.userInfo.find().limit(5);
Equivalent to: selecttop 5 * from userInfo;

16. Query the data after 10 pieces and

copy code as follows:

db .userInfo.find().skip(10);
Equivalent to: select * from userInfo where id not in (
selecttop 10 * from userInfo
);

17. Query data between 5-10

Copy code as follows:

db.userInfo.find().limit(10).skip(5);

can be used for paging, limit is pageSize, skip Which page is *pageSize
18, or and query

Copy code code is as follows:

db.userInfo.find({$or: [{age: 22}, {age: 25}]});
Equivalent to: select * from userInfo where age = 22 or age = 25;

19. Query the first piece of data

Copy code as follows:

db.userInfo.findOne();
Equivalent to: selecttop 1 * from userInfo;
db.userInfo.find().limit(1);

20. Query the number of records in a result set

Copy code as follows:

db.userInfo.find({age: {$gte: 25}}).count();
Equivalent to: select count(*) from userInfo where age >= 20;

21. Sort by a column

Copy code The code is as follows:

db.userInfo.find({sex: {$exists: true}}).count();
Equivalent to: select count(sex) from userInfo;

5. Index
1, create

index The code is as follows:

db.userInfo.ensureIndex ({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});

2. Query all indexes of the current aggregated set

Copy code as follows:

db.userInfo.getIndexes();

3. View Total index record size

Copy code as follows:

db.userInfo.totalIndexSize();

4. Read all index information of the current collection

Copy code as follows:

db.users.reIndex();

5. Delete the specified index

Copy code as follows:

db.users.dropIndex("name_1");

6. Delete all index indexes

Copy code as follows:

db.users.dropIndexes();

6. Modify, add, delete collection data
1. Add

Copy code as follows:

db.users.save({name: 'zhangsan', age: 25, sex: true});

The data column of the added data is not fixed, it is based on the added data
2. Modify the

copy code as follows:

db.users .update({age: 25}, {$set: {name: 'changeName'}}, false, true);
Equivalent to: update users set name = 'changeName' where age = 25;
db.users.update({ name: 'Lisi'}, {$inc: {age: 50}}, false, true);
Equivalent to: update users set age = age + 50 where name = 'Lisi';
db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
equivalent to: update users set age = age + 50, name = 'hoho' where name = 'Lisi';

3. Delete

Copy code as follows:

db.users.remove({age: 132});

4. Query, modify and delete

Copy code as follows:

db.users.findAndModify({
    query: {age: {$gte: 25}},
    sort: {age: -1},
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
} );
db.runCommand({ findandmodify : "users",
    query: {age: {$gte: 25}},
    sort: {age: -1},
    update: {$set: {name: 'a2'}, $ inc: {age: 2}},
    remove: true
});

either update or remove is a required parameter; the other parameters are optional.
Parameter Detailed explanation Default value
query Query filter condition {}
sort If multiple documents meet the query filter condition, the first object will be selected in the arrangement specified by this parameter, and the object will be operated {}
remove If true, it will be selected The object will be deleted before returning N/A
update a modifier object
N/A
new If true, will return the modified object instead of the original. In delete operations, this parameter is ignored. false
fields See Retrieving a Subset of Fields (1.5.0+)
All fields
upsert Creates a new object if the query result is empty. Example (1.5.4+)
false
7. Statement block operation
1. Simple Hello World

copy code The code is as follows:

print("Hello World!");

This writing method calls the print function, and directly writes "Hello World!" The effect is the same;
2. Convert an object to json

. Copy the code as follows:

tojson(new Object());
tojson(new Object('a'));

3. Add data cyclically.

Copy code as follows:

> for ( var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };

this way 30 pieces of data are added in a loop, and the parentheses can also be omitted.

Copy code as follows:

> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age : 22 + i, sex: i % 2});

It is also possible, when you use db.users.find() to query, if multiple pieces of data are displayed but cannot be displayed on one page, you can use it to view the information on the next page;
4. Find cursor query

Copy code The code is as follows :

>var cursor = db.users.find();
> while (cursor.hasNext()) {
    printjson(cursor.next());
} In

this way, all users information can be queried, and the same can be written in this way. The code is as follows: var cursor = db.users.find(); while (cursor.hasNext()) { printjson(cursor.next); } {} can also be omitted 5, forEach iteration loop The code is as follows: db.users.find( ).forEach(printjson); A function must be passed in forEach to process the data information of each iteration 6. Treat the find cursor as an array Copy code as follows: var cursor = db.users.find(); cursor[4]; Get the piece of data with subscript index 4. Since it can be treated as an array, you can get its length: cursor.length(); or cursor.count();























In that way, we can also use loop to display data.

Copy code as follows:

for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);

7. Convert the find cursor to an array

Copy the code as follows:

> var arr = db.users.find().toArray();
> printjson(arr[2]);

use the toArray method to convert it to an array
8, customize our own query results
, only display age < = 28 and only display the data in the age column.

The code is as follows:

db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find( {age: {$lte: 28}}, {age: true}).forEach(printjson);

Exclude the column of age

Copy code as follows:

db.users.find({age: {$lte: 28}}, { age: false}).forEach(printjson);

9. forEach transfer function to display information

Copy code as follows:

db.things.find({x:4}).forEach(function(x) {print(tojson(x)) ;});


8. Others
1. The error information before the query is


copied as follows:

db.getPrevError();

2. The error record is cleared The

copied code is as follows:

db.resetError();

View the basic information of the aggregated collection
1. View the help db.yourColl.help() ;
2. Query the number of data in the current collection db.yourColl.count();
3. Check the data space size db.userInfo.dataSize();
4. Get the db where the current aggregated collection is located db.userInfo.getDB();
5 , Get the current aggregated state db.userInfo.stats();
6. Get the total size of the aggregated set db.userInfo.totalSize();
7. Get the aggregated set storage space size db.userInfo.storageSize();
8. Shard version information db .userInfo.getShardVersion()
9. Rename the aggregated collection db.userInfo.renameCollection("users"); rename userInfo to users
10. Delete the current aggregated collection db.userInfo.drop();


copy the code as follows:

show dbs : Display the database list
show collections: Display the collections in the current database (similar to the tables in the relational database)
show users: Display the users
use <db name>: switch the current database, which is the same as the meaning in MS-SQL
db.help(): display database operation commands, there are many commands in it
db.foo.help(): display set operation commands, there are also Many commands, foo refers to a collection called foo under the current database, not a real command
db.foo.find(): perform data search for the foo collection in the current database (because there are no conditions, it will be listed All data)
db.foo.find( { a : 1 } ): Search for the foo collection in the current database, provided that there is an attribute called a in the data, and the value of a is 1

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326984639&siteId=291194637