首页 > 数据库 >mongodb主要使用规则

mongodb主要使用规则

时间:2022-10-31 20:14:09浏览次数:44  
标签:collectionName 字节 CollectionOptions mongodb 规则 id 使用 public String

mongodb:

ObjectId 的结构:
_id 是集合中文档的主键,用于区分文档(记录),_id自动编入索引。默认情况下,_id 字段的类型为 ObjectID,是 MongoDB 的 BSON 类型之一。如果需要,用户还可以将 _id 覆盖为 ObjectID 以外的其他内容。
ObjectID 长度为 12 字节,由几个 2-4 字节的链组成。每个链代表并指定文档身份的具体内容。以下的值构成了完整的 12 字节组合:
一个 4 字节的值,表示自 Unix 纪元以来的秒数
一个 3 字节的机器标识符
一个 2 字节的进程 ID
一个 3字节的计数器,以随机值开始

timestamp=1667195912
counter=8344334
randomValue1=9390319
randomValue2=3470
在mongod里面635f64087fdf9f0d8e7f530e会解析称上面的结构,
以_id查询时,需要用org.bson.types里面的这个方法,(parseHexString会把字符串形式的ID以16进制解析成ObjectI结构去查询
直接用字符串以Criteria.where("_id").is("635f64087fdf9f0d8e7f530e")查询不出来
 public ObjectId(String hexString) {
        this(parseHexString(hexString));
    }
  HashMap one = mongoTemplate.findOne(new Query().addCriteria(Criteria.where("_id").is(new ObjectId("635f64087fdf9f0d8e7f530e"))), HashMap.class, collectionName);
        Object id = one.get("_id");
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>:" + id.toString());


mongodb定长集合:

API:   
   public MongoCollection<Document> createCollection(String collectionName, @Nullable CollectionOptions collectionOptions) {
        Assert.notNull(collectionName, "CollectionName must not be null!");
        return this.doCreateCollection(collectionName, this.convertToDocument(collectionOptions));
    }

用 CollectionOptions构建定长构造方法,原有的定长构造方法已经不推荐使用
 /** @deprecated */
    @Deprecated
    public CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped) {
        this(size, maxDocuments, capped, (Collation)null, CollectionOptions.ValidationOptions.none(), (CollectionOptions.TimeSeriesOptions)null);
    }


CollectionOptions 参数和上面那个参数一样
例子:
 mongoTemplate.createCollection(collectionName,
                        CollectionOptions.empty().capped().size(1024).maxDocuments(50))
Long size:定长集合容量单位B
maxDocuments:定长集合最大文档数
capped:设置为true未开启定长集合,不然默认就是普通集合



 

增:

批量新增:
public <T> Collection<T> insert(Collection<? extends T> batchToSave, Class<?> entityClass)
单个新增:
public <T> T insert(T objectToSave, String collection

 

查找:
public <T> List<T> findAll(Class<T> entityClass, String collectionName) 
根据条件查找:
List<User> users = mongoTemplate.find(new Query().addCriteria(where("xxxx").is("xxxxx")), User.class);
查找一个:
 public <T> T findOne(Query query, Class<T> entityClass) 
查找某个集合里面一个:
 public <T> T findOne(Query query, Class<T> entityClass, String collectionName) 

 

标签:collectionName,字节,CollectionOptions,mongodb,规则,id,使用,public,String
From: https://www.cnblogs.com/wangbiaohistory/p/16845577.html

相关文章