mongodb基本操作 ## 插入 ``` db.test.insert( { item : "card", qty : 15 }) db.test.insert( [ { _id: 11, item: "pencil", qty: 50, type: "no.2" }, { item: "pen", qty: 20 }, { item: "eraser", qty: 25 } ] ) ``` ## 查询 ``` # 查询全部 test是表名 db.test.find() # 过滤查询 db.test.find({"TickerID":"123"}) # 查询大于100的;此外还有 $gte $lt $lte db.test.find({TickerID : {$gt : 100}}) # 同时匹配 db.col.find({TickerID : {$lt :200, $gt : 100}}) # or查询 db.test.find({$or: [ {'TickerID': {'$gt': 70}}, {'TickerID': {'$lt': 40}} ]}) ``` ## 删除 批量删除,传入条件 ``` db.test.deleteMany({ticker_id:8649569}) ``` ## 创建索引 ``` db.test.createIndex({ticker_id: 1},{background: true}) db.test.createIndex({src_ip: 1},{background: true}) db.test.createIndex({dst_ip: 1},{background: true}) db.test.createIndex({ src_ip: 1, dst_ip: 1 },{background: true}) // 查询索引 db.test.getIndexes() ``` ## 导入json文件到db中 ```bash mongoimport -d databaseName -c collectionName --upsert test1.json ``` ## 复杂json子字段查询 find subdocuments from complex json 对于结构复杂的json,匹配其中的一个子字段,可以使用`.`来层层解开,并且可以指定返回一个子字段 ```bash db.test.find({"job.content.writer.parameter.tid": {"$eq" : 't_dim_config_netidcexit'}} , {"job.content.reader.parameter.connection.querySql":1}); ``` ## aggregate流式处理 对于查询的结果需要做一些处理,可以使用`aggregate` ```bash db.test.aggregate([ {"$match": {"job.content.writer.parameter.tid" : 't_dim_config_netidcexit'}}, {$project: { 'sql': '$job.content.reader.parameter.connection.querySql'}}, {$unwind: "$sql"}, {$unwind: "$sql"} ]); ``` 来自 大脸猪 写于 2021-12-16 10:26 -- 更新于2024-08-15 15:16 -- 1 条评论