Skip to content

Instantly share code, notes, and snippets.

@ilantoren
ilantoren / mongo_requests_c.rs
Last active November 16, 2021 09:45
Creating and using a mongodb Client
/** This is not compiler ready
from cargo.toml:
dependencies.mongodb]
version = "2.0.0"
default-features = false
features = ["sync"]
**/
use mongodb::{bson::Bson, bson::doc, bson::Document, options::ClientOptions, options::FindOptions, sync::Client, sync::Collection};
use mongodb::options::AggregateOptions;
@ilantoren
ilantoren / mongo_requests-get.rs
Created November 16, 2021 10:29
Example of two HTTP get routes
// Get a list of neighborhoods note that collection.distinct returns a Vec<Bson> wrapped in a Result
#[get("/neighborhoods", format="json")]
async fn neighborhoods(client:&State<Box<Client>>) -> Json<Vec<Bson>> {
let collection: Collection<Document> = client.database("sample_restaurants").collection("neighborhoods");
let names = collection.distinct("name", None, None);
let vec = names.unwrap();
Json(vec)
}
#[get("/cuisines", format="json")]
@ilantoren
ilantoren / Routing.kt
Last active November 22, 2021 13:11
Mongo Loves Data Kotlin and Ktor
package go.restuarnt_geo.plugins
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.mongodb.client.model.Accumulators.sum
import com.mongodb.client.model.Aggregates.*
import com.mongodb.client.model.Filters.*
import com.mongodb.client.model.Projections.exclude
import com.mongodb.client.model.geojson.MultiPolygon
@ilantoren
ilantoren / Reactive-example..java
Created November 22, 2021 09:46
Using Java to connect the reactive-streams driver
void run() {
/*
* Requires the MongoDB Java Driver.
* https://mongodb.github.io/mongo-java-driver
*/
Dotenv dotenv = Dotenv.configure().load();
dotenv.entries().forEach(e -> System.setProperty(e.getKey(), e.getValue()));
Bson filter = new Document();
ConnectionString connectionString = new ConnectionString(
// "mongodb+srv://sampleUser:J5DYEzg17UPZPy2V@mflix.beal2.mongodb.net/sample_mflix?authSource=admin&replicaSet=atlas-a7tqy4-shard-0&connectTimeoutMS=7000&maxPoolSize=50&wTimeoutMS=2500&readPreference=primary&appname=MongoDB%20Compass&ssl=true"
@ilantoren
ilantoren / App.tsx
Last active December 12, 2021 13:48
Entry to Realm MERN React
import React from 'react';
import logo from '../logo.svg';
import './App.css';
import * as Realm from "realm-web";
import {ComboBox} from "./Restaurants";
import {Button} from "@mui/material";
const REALM_APP_ID = 'restaurantapp-bfnrh';
console.log("DATA", REALM_APP_ID )
export const app: Realm.App = new Realm.App({ id: REALM_APP_ID });
@ilantoren
ilantoren / Restaurants.tsx
Last active December 12, 2021 13:56
Restaurant Dropdown
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import {Container} from "@mui/material";
import * as Realm from 'realm-web';
import React from "react";
import {RestaurantTable} from "./RestaurantTable";
interface AutocompleteOption {
label: string;
}
@ilantoren
ilantoren / RestaurantTable.tsx
Created December 12, 2021 06:06
realm query ream query
import React from "react";
import * as Realm from "realm-web";
import {app} from "./App";
import { Document } from 'mongodb'
import {DataGridRestaurants} from "./RestaurantDataGrid";
export const RestaurantTable: React.FC<{ neighborhood: String }> = ({neighborhood}) => {
let [data, setData] = React.useState<Document[] > ([])
let [last, setLast] = React.useState<String> ("")
@ilantoren
ilantoren / test_usda.rs
Last active January 25, 2022 08:21
Example of reading a struct from mongodb
#[derive(Serialize,Deserialize, Debug)]
pub struct Usda {
id: String,
product_name: String,
url: String
}
impl fmt::Display for Usda {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "id: {} product: {} url: {} ", self.id, self.product_name, self.url)
}
@ilantoren
ilantoren / create_usda.rs
Created January 25, 2022 09:36
Creating Usda objects from Document
async fn create_usda_set<'a>(client: &Client) {
let read_database = client.database(DB).collection::<Document>(SOURCE);
// as opposed to javascript/python/kotlin the projection is part of the find_options. The batch size is something you want to
// have with the async driver and arguably also with the sync since long queries can lose the cursor.
let find_options = FindOptions::builder().projection( doc!{"id":1, "product_name":1, "sources.url":1}).batch_size(1000).build();
// filter to look for records with a creator : usda and with a sources.url field
let filter = doc!{ "$and": [ { "creator": {"$regex": r"\busda\b", "$options": "i" }}, {"sources.url": {"$exists": 1}}]};
let cursor = read_database.find(filter, find_options).await;
match cursor {
Ok( mut cur) => {
@ilantoren
ilantoren / Process.kt
Last active February 8, 2022 07:33
Distance-Matrix with Google Cloud Scheuduler
package mongolovesdata
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.github.cdimascio.dotenv.Dotenv
import io.github.cdimascio.dotenv.dotenv
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import io.ktor.client.statement.*