Open3

[MongoDB]使い方メモ

しんのすけしんのすけ

ローカル立ち上げ

# docker-compose.yml
# Use root/example as user/password credentials
version: '3.1'

services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    ports:
      - 27017:27017
    volumes:
      - ./mongodb_data:/data/db
      - ./configdb:/data/configdb

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

しんのすけしんのすけ

TypeScriptで接続

// src/index.ts
import mongoose from 'mongoose';

(async () => {
  const databseName = 'testdb';

  // MongoDB
  const { connect, connection, model, Schema, Types } = mongoose;

  await connect(`mongodb://root:example@localhost:27017/${databseName}`, {
    connectTimeoutMS: 1000,
    authSource: 'admin',
  });

  const testSchema = new Schema({
    id: Types.ObjectId,
    key: String,
    key2: String,
    createdAt: Date,
  });

  // Model
  const testModel = model('test', testSchema);

  // insert
  const test = await testModel.create({ key: 'value', createdAt: new Date() });
  console.log(test);

  // update
  await testModel.findOneAndUpdate(test._id, { $set: { key2: 'value2' } });

  // select
  const tests = await testModel.find();
  console.log(tests);

  // delete
  await testModel.deleteOne({ _id: test._id });

  await connection.close();
})();
しんのすけしんのすけ

aggregate集

valueを特定の文字列「-」で分割する

    [
        {
            "$project" : {
                "key" : {
                    "$split" : [
                        "$value",
                        "-"
                    ]
                },
            }
        }
    ],

valueが空ではないときにkeyが1と出力する

    [
        {
            "$project" : {
                "key" : {
                    "$cond" : {
                        "if" : {
                            "$eq" : [
                                "$value",
                                undefined
                            ]
                        },
                        "then" : 0
                        "else" : 1
                    }
                },
            }
        }
    ],

valueが配列のとき、配列の最初の要素を出力する

    [
        {
            "$project" : {
                "key" : {
                    "$arrayElemAt" : [
                        "$value",
                        0
                    ]
                }
            }
        }
    ],