I'm trying to make something similar to Trello.com. There will be many boards, and each board can have many lists, and each lists can have many items. The order of the lists and items can change often by the user, so I came up with something like this that would minimize queries. I just read some of the mongo documentation last night so I would appreciate any feedbacks and suggestions
Here is a list of boards:
{
boards: [
{
_id: 901292190
name: 'board1'
}
]
}
Here is when you view a single board:
{
_id: 901292190
name: 'board 1',
lists: [
{
_id: 932092,
name: 'todo',
items: [
{
_id: 9320903,
name: 'go shopping',
priority: 1,
createdby: 'user1',
assignedto: 'user2'
},
{
_id: 3902901,
name: 'go to school',
priority: 2,
createdby: 'user1',
assignedto: 'user2'
}
]
},
{
name: 'finished',
items: [
{
_id: 91209,
name: 'programming',
priority: 1,
createdby: 'user1',
assignedto: 'user2'
}
]
}
]
}
Related
Given the following MongoDB collection groups:
[{
_id: 'g1',
name: 'Group 1',
projects: [{
_id: 'p1',
name: 'Project 1',
tasks: [{
_id: 't1',
name: 'Task 1'
}, {
_id: 't2',
name: 'Task 2'
}]
}]
}]
I need to find task with _id = t2 and return the whole task object:
{
_id: 't2',
name: 'Task 2'
}
I'm able to find the group, either using mongodb:
db.groups.find({ 'projects.tasks._id': ObjectId('t2') })
Or with Mongoose:
Groups.findOne({ 'projects.tasks._id': 't2' })
But of course, this returns the entire group document, and not the task.
I've tried:
db.groups.aggregate([
{
$match: { 'projects.tasks._id': ObjectId('t2') }
}, {
$replaceRoot: {
newRoot: '$chapters.sections'
}
}
])
But this throws an error.
First of all, I am using Algolia JavaScript API Client V3 (Deprecated)
I have the following records
{
category: SEDAN,
manufacturer: Volkswagen,
id: '123'
},
{
category: COUPE,
manufacturer: Renault,
id: '234'
},
{
category: SEDAN,
manufacturer: Fiat,
id: '345'
},
{
category: COUPE,
manufacturer: Peugeot,
id: '456'
},
{
category: SUV,
manufacturer: Volkswagen,
id: '567'
}
I want to query Algolia and get something similar to the following json
{
categories: {
SEDAN: {
count: 2
items: [{
Volkswagen: {
count 1,
items: [{
id: '123'
}]
}
},
{
Fiat: {
count 1,
items: [{
id: '345'
}]
}
}]
},
COUPE: {
count: 2
items: [{
Renault: {
count 1,
items: [{
id: '234'
}]
}
},
{
Peugeot: {
count 1,
items: [{
id: '456'
}]
}
}]
},
SUV: {
count: 1,
items: [{
Volkswagen: {
count 1,
items: [{
id: '567'
}]
}
}]
}
}
}
I have been trying to query Algolia
index
.search({
query: '',
facets: ['category', 'manufacturer'],
attributesToRetrieve: []
})
.then((result) => {
console.log(result.facets);
});
But I am not sure if it is possible to combine the facets
facets added to a query doesn't work that way. It will simply return the record count for each facet value, not the actual records (https://www.algolia.com/doc/api-reference/api-parameters/facets/)
You can create filters around facets and use those to display results by facet value, but there isn't a way to build a single response JSON that is already grouped by facets like you show above. https://www.algolia.com/doc/api-reference/api-parameters/filters/
I am very new to mongoDB and mongoose and I also know questions like this has been already asked but still I didn't get any luck.
So what I am trying to do is I have 2 collections one is products and second is categories and I am trying to get the products that are of category type: fruits
product.model.js
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
},
name: {
type: String,
required: true,
unique: true
},
price: {
type: Number,
required: true
},
image: {
type: String,
required: true
},
description: {
type: String,
required: true
}
})
const Product = mongoose.model('Product', productSchema)
module.exports = Product
category.model.js
const mongoose = require('mongoose')
const categorySchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
lowercase: true
}
})
const Category = mongoose.model('Category', categorySchema)
module.exports = Category
products collecction
[ { _id: 5ffc9795355f3707ec326f51,
name: 'apple',
price: 80,
image: 'apple1.jpg',
description:
'Do you really need description for this ??',
category: 5ffc94e8a7542a37101a119c,
__v: 0 },
{ _id: 5ffd54409793c33b183376b8,
name: 'Beef',
price: 180,
image: 'beef1.jpg',
description: 'Don\'t you dare to ask about beef in india',
category: 5ffc94dda7542a37101a119b,
__v: 0 },
{ _id: 5ffd54969793c33b183376b9,
name: 'Mango',
price: 100,
image: 'mango1.jpg',
description:
'Have some manog because you cannot eat the bottle of slice like katrina kaif do, its crazy',
category: 5ffc94e8a7542a37101a119c,
__v: 0 } ]
categories collection
[ { _id: 5ffc947ea7542a37101a119a, name: 'vegitables', __v: 0 },
{ _id: 5ffc94dda7542a37101a119b, name: 'non-veg', __v: 0 },
{ _id: 5ffc94e8a7542a37101a119c, name: 'fruits', __v: 0 } ]
Now I want to the get the products whose category are fruits
I know I have to use aggregation and lookup for this I also tried but didn't get any luck, this is my code
const Product = require('./models/product')
const Category = require('./models/category')
const test = async () => {
try {
var query = [
{
$lookup: {
from: "product",
localField: "category",
foreignField: "_id",
as: "product"
}
}]
const productCate = await Product.aggregate(query)
console.log(productCate)
// const productCat = await Product.find().populate({
// path: 'category',
// match: {name: 'fruits'}
// }).exec()
// console.log(productCat)
}catch(e) {
}
}
test()
UPDATE-1
I also tried ppuplate but still didn't get the response as expected, this is my code:
const test = async () => {
try {
const productCat = await Product.find().populate({
path: 'category',
match: {name: 'fruits'}
}).exec()
console.log(productCat)
}catch(e) {
}
}
test()
this is my output
[ { _id: 5ffc9795355f3707ec326f51,
name: 'apple',
price: 80,
image: 'apple1.jpg',
description:
'Do you really need description for this, how dumb are you ??',
category: { _id: 5ffc94e8a7542a37101a119c, name: 'fruits', __v: 0 },
__v: 0 },
{ _id: 5ffd54409793c33b183376b8,
name: 'Beef',
price: 180,
image: 'beef1.jpg',
description: 'Don\'t you dare to ask about beef in india',
category: null,
__v: 0 },
{ _id: 5ffd54969793c33b183376b9,
name: 'Mango',
price: 100,
image: 'mango1.jpg',
description:
'Have some manog because you cannot eat the bottle of slice like katrina kaif do, its crazy',
category: { _id: 5ffc94e8a7542a37101a119c, name: 'fruits', __v: 0 },
__v: 0 } ]
Here I also get the beef that is fall under non-veg category but with the category null. Actually I only want the fruits category products.
you can following this code
const test = async () => {
try {
let categoryId = await Category.findOne({name:"fruits"}).select("_id")
const productCat = await Product.find({category:categoryId}).populate(
"category"
).lean()
console.log(productCat)
}catch(e) {
}
}
test()
you can do with with populate match without using aggregation:
Product.find().populate({
path: 'category',
match: { 'name': 'fruits' }
})
.exec()
I have a dataset with metrics collected from a group of sensors.
My dataset looks like this:
{type: 1, display: 'foo', value: 'A'}
{type: 2, display: 'bar', value: 'B'}
{type: 2, display: 'foo', value: 'B'}
I am trying to aggregate the results and get some meaning insights via a REST API. I am somehow trying to produce aggregated results as:
[{
type: 1,
displays: [
{
name: 'foo',
count: 1
}
],
values: [
{
name: 'A',
count: 1
}
],
total_count: 1
},{
type: 2,
displays: [
{
name: 'foo',
count: 1
} , {
name: 'bar',
count: 1
}
],
values: [
{
name: 'B',
count: 2
}
],
total_count: 2
}]
Summarizing the aggregated results and producing shallow results is straight forward, I am struggling though as I can't created the nested counters for types and displays all together.
I have tried to use various aggregation operators with no luck.
Basically I can get one group by types or displays as:
db.logs.aggregate([
{
$group: {
_id: {
type: '$type',
display: '$display'
},
count: { $sum: 1 }
}
}, {
$group: {
_id: '$_id.type',
displays: {
$push: {
name: "$_id.display",
count: "$count"
}
}
}
}
]);
Any help will be highly appreciated.
I have this schema:
{
user: { type: String, required: true },
pass: { type: String, required: true },
tokens: [String],
book: {
cards: [{
id: String,
copies: Number
}],
groups: [String],
users: [String],
orgs: [String],
stats: {
}
},
decks: [{
name: String,
description: String,
cards: [{
id: String,
copies: Number
}],
groups: [String],
users: [String],
orgs: [String],
stats: {
}
}],
groups: [String],
orgs: [String]
}
I have two supplied parameters: 'user' and 'access_user', the array schema.book.users[] may or may not contain 'access_user'. The array schema.decks[i].users[] may or may not contain 'access_user'. eg:
{
user: 'bob',
pass: 'secret',
tokens: ['8ht490g'],
book: {
cards: [...],
groups: [...],
users: ['NOPE'],
orgs: [...],
stats: {
...
}
},
decks: [{
name: 'deck1',
description: ...,
cards: [...],
groups: [...],
users: ['access_user'],
orgs: [...],
stats: {
...
}
},
{
name: 'deck2',
description: ...,
cards: [...],
groups: [...],
users: ['NOPE'],
orgs: [...],
stats: {
...
}
}],
groups: [...],
orgs: [...]
}
With the compare user 'bob' 'access_user'.
I want this in return:
{
user: 'bob',
decks: [{
name: 'deck1',
description: ...,
cards: [...]
}]
}
I tried a few things, nothing seems to be working. model.find() will not work what I need is complex enough. Aggregation is really the only way. I am just not sure how to build it.
This is what I was trying:
model.aggregate([
{ $match: { user: 'bob' } },
{ $project: {
'book.users': { $match: 'access_user' }
}},
{ $project: {
'decks.users': { $match: 'access_user' }
}}
]);
I am pretty sure none of this is correct, but, I do not fully understand MongoDB's aggregate system.
Aggregation is pretty complicated but it basically pipes your response. Try this:
model.aggregate([
{ $match: {
$and: // match multiple
{'user': 'bob'},
{'deck.users': 'access_user' }
}
},
{$project:{ // render each match in this format. output an array.
"user": 1,
"decks": 1
}}
])
Try this if it doesn't work. Comments added so you can understand each command.
UPDATED.
model.aggregate(
{$match: {'user':'bob'}},
{$unwind: "$decks"},
{$match: {"decks.users":"access_user"}})