How to check if a collection exists

Hello everybody,

I try to check if a collection exists to know if is the first execution

First, I connect with MongoDBAtlas successfully:

cliente_local, err := mongo.NewClient(
		options.Client().ApplyURI(
			useful.CadenaConexion))
	useful.Check(fmt.Errorf("[-]It cannot create Newclient", err))

	ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
	err = cliente_local.Connect(ctx)
	if err != nil {
		useful.Check(fmt.Errorf("[-] It cannot create Connect", err))
	}
	defer cancelar()

	// Check the connection
	err = cliente_local.Ping(ctx, nil)

	useful.Check(fmt.Errorf("[-]It cannot Ping", err))

	log.Println("[+]Connected to MongoDB Atlas")

After I use a function to check if a collection exists:

var coll *mongo.Collection = mongo_cliente.Collection("config")

	exists = true

	// Find the document for which the _id field matches id.
	// Specify the Sort option to sort the documents by age.
	// The first document in the sorted order will be returned.
	opts := options.FindOne()
	var result bson.M

	filter := bson.D{{Key: "first_run", Value: true}}

	err := coll.FindOne(
		context.TODO(),
		filter,
		opts,
	).Decode(&result)

** Is there another way to check if a collection exists, anyway, with my code does not work :frowning: **

Thanks in advance!!

Here is the simple snip code to print all the collection names for you DB, once you get all the collections you can check if the the collection is present or not.

Please do let me know if you are looking for something else.

	clientOpts := options.Client().ApplyURI(uri)
	client, err := mongo.Connect(ctx, clientOpts)
	if err != nil {
		log.Fatal(err)
	}

	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		log.Println("mongoDB is down")
		log.Fatal(err.Error())
	}

	cNames, err := client.Database("company").ListCollectionNames(ctx, bson.D{})
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(cNames)


2 posts were split to a new topic: Is there an easier way to create time series collections in Go?