Push into an array of documents in mongodb - javascript

Which operator to use to push a new question into array of question?I have got the document in following format.Which mongo db operator to use to insert a new question into array of questions provided that i am given chapterId and subchapterId in advance.
For example i want to insert a new question in subchapterId "1".
{
"chapterId": "38",
"subChapter": [
{
"subchapterId": "1",
"questions": [
{
"title": "Either his however modern. Stop central owner color type out. Interview five beyond interesting type suddenly.",
},
{
"title": "Amount himself foreign color moment gun together sit. Deal race range heart despite several. Rather activity eat dinner save mission western. Civil past public enter four then.",
},
{
"title": "Four former operation. Class continue away treatment.\nResponsibility condition dinner realize everything. Sign scene order quality yet. Within sing statement skill popular southern whole."
},
{
"title": "Where of coach nature ask page allow.\nType exist hotel time. Central site policy everyone safe. Official administration family somebody.",
},
{
"title": "Necessary dark these much region. Form sometimes seek. Future according detail piece section.\nNear everything admit. Senior Republican draw as expert market.",
}
]
},
{
"subchapterId": "2",
"questions": [
{
"title": "Audience still use group. Yourself building police. Play imagine serious reality population reach.\nHerself without member must think concern window finish."
},
{
"title": "Rule trip manage still. Imagine religious above race something successful.\nOnce base American series. Low page quite allow. Customer maybe base leave way under blood.",
},
{
"title": "Church audience anyone garden. Federal when individual style.Value billion morning need box whether. Coach traditional cold each us truth.",
}
]
}
]
}

You can try this
const title = "this is the new question"
db.collection.update(
{ "subChapter.subchapterId": "1" },
{ "$push": { "subChapter.$.questions": { title } }}
)

You can use $push along with update
Example code is for chapterId:38 and subchapterId:1
db.collection_name.update({ "chapterId":"38", "subChapter.subchapterId": "1" }, { $push: { "subChapter.$.questions":{'title':'Newly added record'} }})

use $addToSet Which avoids the Duplicates in the Array of objects while updating
db.yourcollectionName.update({
"subChapter.subchapterId" :"1"
},{$addToSet:{"subChapter.$.questions":{title:"updated Object"}}})

Related

For Prisma Client join queries is it possible to move deeply nested fields to top level of result?

Does Prisma have the ability to move nested fields from another table join to the top level of the result, like a flattened view? I want to put the result JSON into a frontend table without digging through nested objects and building another object.
For example I want to replicate this behavior where I can pick and choose the columns from different tables (columns from User, and School). Currently I use a raw query with a similar SQL, however I wonder if it's possible with using only the Prisma API:
SELECT
u.id
, u.email
, s.school_name
FROM "User" AS u
JOIN "UserSchool" AS us ON us.user_id = u.id
JOIN "School" AS s ON s.id = us.school_id
id | email | school_name
123| student1#email.com | mount high
I want JSON that looks like this:
{
"id": "1",
"email": "student1#email.com",
"school_name": "mount high",
}
If I did this in Prisma, I would need to go into several levels of nested objects to get the same column name on another table for e.g. user[user_school][schoo][school_name]. This requires extra work to loop through all my results, extract from the nested object, and build another object. This example isn't too bad, but I have more joins and deeply nested objects for my actual problem (lots of association/lookup tables). I've experimented with the select and include for my joins, but they are structured with the nested JSON.
users = await prisma.user.findMany({
include: {
user_school: {
include: {
school: true,
},
},
},
{
"id": "1",
"email": "student1#email.com",
"user_school": [
{
"id": 1,
"user_id": "1",
"school_id": "1",
"school": {
"id": 1,
"school_name": "mountain high",
}
}
],
}
It's not possible to flatten out the results as of now.
The only way to achieve this would be by using rawQuery as you mentioned.
However, there is an existing Feature Request which discusses Flattening out the results by providing an option of flatten:true. If you could mention your use case there and add a comment it would help Prisma's Product and engineering team in prioritising it.

How to filter JSON data based on attributes?

I have the following JSON data.
{
"partners": [
{
"logo": "school-of-bookkeeping.png",
"title": "Schoolofbook<br class='d-none d-md-inline-block'/>keeping.com",
"websiteURL":"https://www.schoolofbookkeeping.com",
"getInTouchURL":"https://www.schoolofbookkeeping.com",
"location":"Santa Monical, CA, US",
"servicesCategories":["Consulting Services","Webgility Setup"],
"accountingSoftware":["QuickBooks Online","QuickBooks Enterprise","QuickBooks Point of Sale"],
"onlineStore":["Magento","Shopify","WooCommerce"],
"marketplace":["Amazon","eBay","Etsy"],
"description": "Teaching Businesses and Accounting Professionals the ins and outs of ecommerce.",
"longDescription":"<p class='fs-16 lh-1-5'>Let's face it; ecommerce is hard. From tracking inventory, sales tax requirements, shipping fulfillment, and general bookkeeping, keeping pace with all the requirements and business workflows is difficult. That's why we have partnered with Webgility to create a learning resource to provide small and medium-sized businesses a seamless and path from setup to implementation, so the accounting is done so that can focus on running your business, rather than your business, rather than running yourself ragged.</p><p class='fs-16 lh-1-5'>Our lifelong learners are here for hire so you can be set up for success and have a trusted advisor to guide you through setup to implementation.</p>",
"servicesWeProvide": "<p class='fs-16 lh-1-5'>Website creation to e-commerce implementation.</p>",
"featured": false,
"partnerType": "Certified",
"link": "school-of-bookkeeping",
"customClass": "school-of-bookkeeping"
},
{
"logo": "danwidth.png",
"title": "Danwidth",
"websiteURL":"https://www.danwidth.com",
"getInTouchURL":"https://completebusinessgroup.com/danwidth/",
"location":"Tucson, AZ, US",
"servicesCategories":["Consulting Services","Webgility Setup"],
"accountingSoftware":["QuickBooks Online","QuickBooks Enterprise","QuickBooks Point of Sale"],
"onlineStore":["Magento","Shopify","WooCommerce"],
"marketplace":["Amazon","eBay","Etsy"],
"description": "Put your ecommerce bookkeeping on cruise control.",
"longDescription":"<p class='fs-16 lh-1-5'>I don't want to be your bookkeeper. I transform businesses through technology by creating automagic workflows that allow your bookkeeping to be handled \"by accident.\" Imagine entering data once, or not at all, and your bookkeeping is done for you. Specializing in brick and mortar retail and ecommerce, I will set up your services to integrate so that your accounting and bookkeeping is done for you as a result of you simply running your business. We work with a host of solution providers that all integrate into your accounting platform that will enable you to make informed business decisions in real-time.</p><p class='fs-16 lh-1-5'>My expertise is unparalleled across all of Intuit's Small business platforms. Online or Desktop, including Point of Sale, if it can be done in QuickBooks, I know how to make it happen. In addition, we partner with other business services to increase your revenue, decrease your expenses, and widen your online presence.</p>",
"servicesWeProvide": "<p class='fs-16 lh-1-5'>End-to-end services from website creation, digital marketing, ecommerce platform to bookkeeping, payroll service setup, and support.</p>",
"featured": false,
"partnerType": "Certified",
"link": "danwidth",
"customClass": ""
}
]
}
How can I filter this on the basis of servicesCategories, accountingSoftware, onlineStore, marketplace, and partnerType?
I want to filter data with $.getJSON() method with on change select box value.
That depends on how you want to go about filtering. There are a few different ways to accomplish this, here is one function that allows you to pass in the key you want to filter on and an array of values to filter by:
let filterBy = (list, keyToFilter, filters) => {
// Allow a string to be passed in
if(!Array.isArray(filters)) filters = [filters];
return list.filter(item => {
let values = item[keyToFilter];
// Check if the filter exists
if(!values) return false;
// For items that aren't arrays, like partnerType
// This makes it compatible with the conditional
// below, where the logic for check happens.
if(!Array.isArray(values)) values = [values];
// Check if array of your filters matches any in list
return filters.some(n => values.includes(n));
}
);
};
Then you can call this on your list like so:
let list = { "partners": [
...
]};
let accountingSoftware = filterBy(list["partners"], "accountingSoftware", ["QuickBooks Online","QuickBooks Enterprise"]);
let partnerType = filterBy(list["partners"], "partnerType", "Certified");
Here is an example if you want to play around with it more, https://repl.it/#BenjaminKnox/filter-json

Adding and removing items from a cart in Dialogflow

I am prototyping a Food Ordering app using Dialogflow(Chatbot maker) and got stuck with this problem. Technically, I want to persist the gathered data from an Intent after the user decided to "add more items to their order" and satisfies all the required parameters, which are, (itemName, quantity, [variants], [sauceType], ...).
The chat bot should be able to handle a request which consist of multiple items with their corresponding quantities but I am not sure if it's possible to model a data wherein it consist an array of Entities so, my first thought was to use a persistent Fulfillment using session-based Webhook with our custom Web Service, like for example: foodorder/api/order/123/items/add and 123 being the Session Id. But this approach requires more work and the generated model can be difficult to translate in Dialoflow Console.
The second solution comes into my mind, is to leverage the Intent property called Action and Parameters where we mark the Entity as List, but using this approach, the quantity doesn't get attached to the item itself.
My question is, how can I be able to model a data using Dialogflow that resembles something like below:
{
"givenName": "Dummy User",
"order": [
{
"itemName": "Burger",
"quantity": 2
},
{
"itemName": "6 piece Chicken Nuggets",
"quantity": 1,
"sauceType": "Tangy Barbeque"
},
{
"itemName": "Coke",
"quantity": 1,
"size": "Small"
}
]
}
Turns out what I was looking for was Composite Entities and mark it as a list.
The detailed answer can be found on this link:
https://stackoverflow.com/a/47166123/2304737

Show suggestion from different indexes of elasticsearch?

Suppose I have two indexes in elasticsearch. First names contains five values Ram, Shyam, Hari, Dipu, Kishan and second profession contains five values like teacher, driver, doctor, bank manager, salesman. When someone types Ra, I want to show suggestions like
Ram is teacher
Ram is driver
Ram is doctor
Ram is bank manager
Ram is salesman
Similarly when someone types Har, I want to show
Hari is teacher
Hari is driver
Hari is doctor
Hari is bank manager
Hari is salesman
I don't want to store every possible combination.
Also suppose user is looking for Ram is a doctor at Raman Hospital since 2002. Here Ram, doctor, Raman Hospital, 2002 belongs to different-different indexes. When user types Ram I want to show suggestions as Ram is a teacher at Basic Boys School Since 2002, Ram is salesman at HUL since 2006. And if there is one more guy with name Raman then Raman is driver at Ola since 2012 should also be shown as suggestion. For such searches is there any good approach available or I have to work on that?
Mapping:
PUT name
{
"mappings": {
"_doc" : {
"properties" : {
"suggest" : {
"type" : "completion",
"contexts": [
{
"name": "userid",
"type": "category"
}
]
}
}
}
}
}
Indexing:
POST name/_doc/
{
"suggest": {
"input": ["BHANU PRAKASH"],
"contexts": {
"userid": ["99569858","99156661","90273758","6598242461","65910563"]
}
}
}

Meteor: how to sort users by most following?

welcom ...
I have in my Meteor project 2 collections
1 - followers
"_id": "_id",
"follower": "username1",
"following": "username2"
}
2- users
"_id": "_id",
"username": "username",
[...]
}
I would like to sort users by the most following how I can do this
can anyone help me ?....
I would suggest putting the 'followers' collection as an object inside each 'users' document. There's no point in putting them in separate collections and then having to reference back and forth based on a user's ID. It's just taking up more space in your DB. Just make an object inside each user called 'follows' or something similar with the same structure (though make 'follower' and 'following' arrays). Something like this:
"users":{
"_id":_id,
"username":"username",
"follows":{
"followers":["username 1","username 2"],
"following":["username 3", "username 4"],
}
}
Once you have it so each user document has it's own 'follows' object, you can sort users by using the 'aggregate' functionality MongoDB Aggregate. This following code sorts based on the length of the followers array. You'd do a separate one for 'following' swapping out '$followers' with "$following".
db.users.aggregate(
[
{
$project: {
"length": { $size: "$followers" }
},
{ "$sort": { "length": -1 } },
}
]
)
This will probably require some tweaking, of course. just helping lead you in the right direction.

Categories

Resources