Query inner ID in MongoDB - mongodb

I have two collections
1)User -> With fields,
name as String
emailId as String
2)
Rating -> With fields,
`userId as String.` (This will be the ID of the user and Foreign Key as per SQL)
comment as String`
I have created a record for the user which looks like
{
"_id": {
"$oid": "565fe1294a27a93449751a9a"
},
"name": "Some name",
"email": "somemail#gmail.com",
"createdAt": {
"$date": "2015-12-03T06:28:57.904Z"
},
"updatedAt": {
"$date": "2015-12-03T06:28:57.904Z"
}
}
I have create a record for the Rating which looks like
{
"_id": {
"$oid": "565fefa30878764428d96be1"
},
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment",
"createdAt": {
"$date": "2015-12-03T07:30:43.409Z"
},
"updatedAt": {
"$date": "2015-12-03T07:30:43.409Z"
}
}
Now I want to make a query where all the rating done by the user along with the user document are returned.
If I make a query like
db.user.find({
"userId" :"565fe1294a27a93449751a9a"
})
I get the result like
{
"id": "565fefa30878764428d96be1",
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment"
}
But I want the user object as well in it something like.
{
"id": "565fefa30878764428d96be1",
"user": { "name": "Some name",
"email": "somemail#gmail.com",
"id": "565fe1294a27a93449751a9a"
},
"comment": "just a test comment"
}
Or even something like this will work as well
"rating": {
"id": "565fefa30878764428d96be1",
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment"
},
"user": {
"id": "565fefa30878764428d96be1",
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment"
}

Here you need to change schema. You need to change user type from string to reference. If you add reference of User in rating, then that will be easy. If you add reference of User schema then you can populate user on rating. Then will get user info with rating.
example of reference :
User: {type: mongoose.Schema.ObjectId, ref: 'User'}

Found my exact solution here. http://sailsjs.org/documentation/concepts/models-and-orm/associations/one-to-many
Technically it creates two queries in the backend. Found this out by the response time.
But anyways it solves my problem.

Related

how to update nested array of object in mongodb

Here is my db collection in mongoDB. I am using mongoose to update the data inside the comments array
{
"author": {
"email": "user#example.com",
"userName": "John"
},
"_id": "63bc20741475b40323d6259f",
"title": "this is blog",
"description": "description",
"blogBanner": "https://github.com//routers/userRouter.js",
"views": "0",
"comments": [
{
"userId": "63b919840ae5303938fb1c17",
"comment": "first comment",
"_id": "_id:63bbdbdb7018eabb752c0e58
},
{
"userId": "63b919840ae5303938fb1c17",
"comment": "second comment",
"_id": "63bbdbdb7018eabb752ce55"
}
],
"reaction": [
{
"userEmail": "gias#gmail.com",
"react": "love"
}
],
"date": "2023-01-09T14:09:32.810Z",
"__v": 0
}
here i want to update the first comment by using comment._id: 63bbdbdb7018eabb752c0e58
how can i update the single comment by using comment._id ;
use-case : when user want to update his/her comment by using comment._id
here i want to update the first comment by using comment._id: 63bbdbdb7018eabb752c0e58
how can i update the single comment by using comment._id;
use-case : when user want to update his/her comment by using comment._id
Please, read the following docs:
https://www.mongodb.com/docs/manual/reference/operator/update/positional/#update-documents-in-an-array
Model.update(
{
'_id': '63bc20741475b40323d6259f',
'comments._id':'63bbdbdb7018eabb752ce55'
},
{ $set: { "comments.$.comment" : 'Edited Text' } }
)

How to get nested "Sequelize" data?

I have created a Sequelize ORM based PostgreSQL database. I have implemented some relation between product and reviews. And, each review has been posted by a user. So, when I am querying for a single product, I want the data with, product, reviews & inside review I want to see who posted as well means user.
{
"id": 1,
"name": "Rounded Neck T-Shirt",
"title": "some title",
"snippet": "some snippet od demin t shirt",
"details": "some details",
"moreInfo": "some moreInfo",
"size": "size will be in a seperate table this will be FK",
"stock": 452,
"askingPrice": 4299,
"offPrice": null,
"offer": null,
"ratings": null,
"images": null,
"pictureUrl": "https://loopinfosol.in/themeforest/ekka-html-v31/ekka-html/assets/images/product-image/6_2.jpg",
"purchaseCost": 4200,
"createdAt": "2022-02-14T10:59:55.999Z",
"updatedAt": "2022-02-14T11:07:12.916Z",
"categoryId": 1,
"userId": 1,
"reviews": [
{
"id": 1,
"rating": 5,
"comment": "Very nice product",
"createdAt": "2022-02-14T17:28:22.680Z",
"updatedAt": "2022-02-14T17:28:22.680Z",
"productId": 1,
"userId": 1
}
]
}
Here, "userId" is the foreign key for the registered user id. I want to see the user data inside "reviews" as well. How can I do that?
I get the above JSON data by querying the following code.
Product.findOne({
include: [Review],
where: { id: req.params.id },
})
If you already have an association definition like Review.belongsTo(User, ... then you simply need to indicate a nested include option with User model:
Product.findOne({
include: [{
model: Review,
include: [{
model: User
}]
}],
where: { id: req.params.id },
})

Rally - Create User Story with tags using REST (non-API)

How do I add/attach tags while creating/updating user stories in Rally? I'm using the below JSON script and I'm getting a error "cannot find referenced object". What am I missing?
{
"HierarchicalRequirement": {
"Description": "As a developer to create a user story",
"Name": "User story to be created",
"Notes": "Created via REST Client",
"Project": {
"_ref": "https://rally1.rallydev.com/slm/webservice/v2.0/project/1302421049",
"_refObjectName": "Sample Project",
"_type": "Project"
},
"Tags": {
"_type": "Tag",
"_tagsNameArray": [{
"Name": "My Tag"
}],
"Count": 1
}
}
}
Thanks in advance,
Leo.
You just need to encode your tags a little differently and you'll have it. Tags (and all collections) expect to be specified as an array of objects with _ref properties like so:
"Tags": [
{
"_ref": "/tag/12345"
},
{
"_ref": "/tag/23456"
}
]

How can I query an indexed object list in mongodb?

I have some documents in the "company" collection structured this way :
[
{
"company_name": "Company 1",
"contacts": {
"main": {
"email": "main#company1.com",
"name": "Mainuser"
},
"store1": {
"email": "store1#company1.com",
"name": "Store1 user"
},
"store2": {
"email": "store2#company1.com",
"name": "Store2 user"
}
}
},
{
"company_name": "Company 2",
"contacts": {
"main": {
"email": "main#company2.com",
"name": "Mainuser"
},
"store1": {
"email": "store1#company2.com",
"name": "Store1 user"
},
"store2": {
"email": "store2#company2.com",
"name": "Store2 user"
}
}
}
]
I'm trying to retrieve the doc that have store1#company2.com as a contact but cannot find how to query a specific value of a specific propertie of an "indexed" list of objects.
My feeling is that the contacts lists should not not be indexed resulting in the following structure :
{
"company_name": "Company 1",
"contacts": [
{
"email": "main#company1.com",
"name": "Mainuser",
"label": "main"
},
{
"email": "store1#company1.com",
"name": "Store1 user",
"label": "store1"
},
{
"email": "store2#company1.com",
"name": "Store2 user",
"label": "store2"
}
]
}
This way I can retrieve matching documents through the following request :
db.company.find({"contacts.email":"main#company1.com"})
But is there anyway to do a similar request on document using the previous structure ?
Thanks a lot for your answers!
P.S. : same question for documents structured this way :
{
"company_name": "Company 1",
"contacts": {
"0": {
"email": "main#company1.com",
"name": "Mainuser"
},
"4": {
"email": "store1#company1.com",
"name": "Store1 user"
},
"1": {
"email": "store2#company1.com",
"name": "Store2 user"
}
}
}
Short answer: yes, they can be queried but it's probably not what you want and it's not going to be really efficient.
The document structure in the first and third block is basically the same - you have an embedded document. The only difference between are the name of the keys in the contacts object.
To query document with that kind of structure you will have to do a query like this:
db.company.find({ $or : [
{"contacts.main.email":"main#company1.com"},
{"contacts.store1.email":"main#company1.com"},
{"contacts.store2.email":"main#company1.com"}
]});
This query will not be efficient, especially if you have a lot of keys in the contacts object. Also, creating a query will be unnecessarily difficult and error prone.
The second document structure, with an array of embedded objects, is optimal. You can create a multikey index on the contacts array which will make your query faster. The bonus is that you can use a short and simple query.
I think the easiest is really to shape your document using the structure describe in your 2nd example : (I have not fixed the JSON)
{
"company_name": "Company 1",
"contacts":{[
{"email":"main#company1.com","name":"Mainuser", "label": "main", ...}
{"email":"store1#company1.com","name":"Store1 user", "label": "store1",...}
{"email":"store2#company1.com","name":"Store2 user", "label": "store2",...}
]}
}
like that you can easily query on email independently of the "label".
So if you really want to use the other structure, (but you need to fix the JSON too) you will have to write more complex code/aggregation pipeline, since we do not know the name and number of attributes when querying the system. Theses structures are also probably hard to use by the developers independently of MongoDB queries.
Since it was not clear let me show what I have in mind
db.company.save(
{
"company_name": "Company 1",
"contacts":[
{"email":"main#company1.com","name":"Mainuser", "label": "main"},
{"email":"store1#company1.com","name":"Store1 user", "label": "store1"},
{"email":"store2#company1.com","name":"Store2 user", "label": "store2"}
]
}
);
db.company.save(
{
"company_name": "Company 2",
"contacts":[
{"email":"main#company2.com","name":"Mainuser", "label": "main"},
{"email":"store1#company2.com","name":"Store1 user", "label": "store1"},
{"email":"store2#company2.com","name":"Store2 user", "label": "store2"}
]
}
);
db.company.ensureIndex( { "contacts.email" : 1 } );
db.company.find( { "contacts.email" : "store1#company2.com" } );
This allows you to store many emails, and query with an index.

Remove entry in an array of a MongoDB document

Say I have a document that looks something like this:
{
"_id": ObjectId("50b6a7416cb035b629000001"),
"businesses": [{
"name": "Biz1",
"id": ObjectId("50b6bc953e47dc923e000001")
}, {
"name": "Biz2",
"id": ObjectId("50b6ccebae0513bf52000001")
}, {
"name": "Biz3",
"id": ObjectId("50b6d015c58b414156000001")
}, {
"name": "Biz4",
"id": ObjectId("50b6d0c8a4cdd5e356000001")
}]
}
I want to remove
{
"name": "Biz3",
"id": ObjectId("50b6d015c58b414156000001")
}
from the array of businesses. I tried this (using business name instead of id for clarity):
db.users.update({'businesses.name':'Biz3'},{$pull:{'businesses.name':'Biz3'}})
but of course it didn't work. I know that the query part is correct because I get the document back when I do this:
db.users.find({'businesses.name' : 'Biz3'})
So the problem is with the update part.
Just ran a quick lil test and this works
I think trying db.users.update({'businesses.name':'Biz3'},{$pull:{'businesses':{'name':'Biz3'}}}) should do it