Monday, August 10, 2020

Mongodb Auspix note

 db.stock.getIndexes();

db.stock.createIndex({"code":1}); 

db.stock.createIndex({"time":1});

db.stock.find( { $and: [ {"code":"SH1A0001"},{"time":{$lte:"20191231 15:00"}}]} ).sort({"time":-1}).limit(1).pretty();

db.stock.distinct("code").length

db.code.find({start_time:{$ne:20200810}}).pretty()


db.stock.find({code:"SH000001"}).sort({time:1}).limit(3).pretty();


db.code.find({end_time:{$ne:""}}).pretty()

db.code.find({$and:[{code:"SH603277"},{end_time:{$ne:""}}]}).pretty()

--sort and limit, need use match

db.stock.aggregate([

{$match:{code:"SH000001"}},

    {"$sort": {"time":-1}},

    {"$limit": 5},

    {"$sort": {"time": 1}}

]).pretty()


--sort and limit

db.stock.aggregate([

{$match:{ $and: [{code:"SH000001"},{time:{$lte:"20200810 15:00"}}] }},

    {"$sort": {"time":-1}},

    {"$limit": 5},

    {"$sort": {"time": 1}}

]).pretty()

The Java implementation:

public List<Stock> getStockList(String code,String timeStr) throws JsonProcessingException {
List<Stock> stockList = new ArrayList<>();
MongoCollection<Document> stockCollection = mongoTemplate.getCollection(stockColName);
AggregateIterable<Document> stockAgg = stockCollection.aggregate(Arrays.asList(match(Filters.and(Filters.eq("code",code),Filters.lte("time",timeStr))),
sort(Sorts.descending("time")),
limit(379),
sort(Sorts.ascending("time"))));
ObjectMapper objectMapper = new ObjectMapper();
for(Document doc:stockAgg){
doc.remove("_id");
Stock stock = objectMapper.readValue(doc.toJson(),Stock.class);
stockList.add(stock);
logger.debug("stock==="+stock);
}
return stockList;
}


distinct multiple fields are pretty not straightforward and not efficient:

both below are not what I expect


db.stock.aggregate( 

[

{"$group": { "_id": { code: "$code", name: "$name" } } }

]

)


db.stock.aggregate([

{$group: {

    _id: null,

    code: {$addToSet: '$code'},

    name: {$addToSet: '$name'}

    }}

])

No comments:

Post a Comment