MongoDB——增删改查

文档结构:

{
    "_id": ObjectId("5d5e5de597eb2f0b70005d1a"),
    "userId": 1234,
    "word_records": [
        {
            "word": "helloo",
            "from": "en",
            "to": "hi",
            "update_time": 1245748,
            "create_time": 235689
        },
        {
            "word": "xx",
            "from": "en",
            "to": "hi",
            "update_time": 1245748,
            "create_time": 235689
        }
    ]
}

一个用户想增加一个单词:

db.getCollection("collect_record").update({'userId':1234},{$addToSet:{word_records:{'word':'update2','to':'en','from':'hi'}}})

一个用户想删除一个单词:

db.getCollection("collect_record").update({"userId":123},{"$pull":{"word_records":{"word":"hello"}}})

分页查询某个用户的单词:

db.getCollection("collect_record").findOne({'userId':123},{'word_records':{$slice:[0,2]}})

 避免重复插入:

https://blog.csdn.net/wu0che28/article/details/82316933

索引:

db.getCollection("collect_record").createIndex({
userId: NumberInt("1"),
"word_records.from": NumberInt("1"),
"word_records.to": NumberInt("1"),
"word_records.word": NumberInt("1")
}, {
name: "userId_1_word_records.from_1_word_records.to_1_word_records.word_1",
unique: true
});

posted @ 2019-08-23 11:35  高圈圈  阅读(152)  评论(0编辑  收藏  举报