I have a collection that consists of posts. Inside those post objects are properties about the post, one of which being an array of tags associated with the post. Inside the array of tags are more objects, each of which are the tags with a name property. I would like to get back all the posts from this collection which have a given tag in them based on the name of the tag.
Here is an example of a post object within the collection:
{
"_id" : ObjectId("5c6a0478cba09c148b497fc6"),
"tags" : [
{
"_id" : "5c69d974e05511106048780e",
"name" : "Food",
"text_color" : "#ffffff",
"bg_color" : "#02569b",
"createdAt" : "2019-02-17T22:00:20.143Z",
"updatedAt" : "2019-02-17T22:00:20.143Z",
"__v" : 0
},
{
"_id" : "5c69d95de05511106048780d",
"name" : "Drinks",
"text_color" : "#ffffff",
"bg_color" : "#0175c2",
"createdAt" : "2019-02-17T21:59:57.758Z",
"updatedAt" : "2019-02-17T21:59:57.758Z",
"__v" : 0
}
],
"title" : "Title of the post",
"body" : "body of the post",
"author_id" : ObjectId("5c5e0d3b647f12e949cbea1e"),
"author_name" : "garrett",
"likes_count" : 1,
"createdAt" : ISODate("2019-02-18T01:03:52.497Z"),
"updatedAt" : ISODate("2019-02-28T00:25:21.969Z"),
"__v" : 0,
"dislikes_count" : 0
}
Of course I have other post objects in this collection, some of which may have different tags. How can I get all posts with the food tag to be returned?
A basic find query will do the job here. Here's how it looks
const tagName = 'food;
db.posts.find({ 'tags.name': tagName }).then(console.log);
Related
I have a mongoose document that is a User. Each user has arrays or words e.g. nouns. I want to be able to update the fields of the words e.g. add a +1 to the frequency or change the status number. I can access the whole array but not the individual items in the array. Also i want to be able to display the items in the array based on their fields e.g. only display those with frequency of 3 or more etc...
I have tried lots of different things but I'm just not getting it. I keep getting back error messages that findOneAndUpdate is not a function, or 'undefined' when I try to access and update documents.
{
"_id" : ObjectId("5f7d8490c1842471c6bcea42"),
"username" : "eric#mail.com",
"nouns" : [
{
"_id" : ObjectId("5f7d849cc1842471c6bcea43"),
"word" : "die Sonne",
"timeStamp" : ISODate("2020-10-07T09:04:28.436Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84a8c1842471c6bcea45"),
"word" : "das Wetter",
"timeStamp" : ISODate("2020-10-07T09:04:40.940Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84afc1842471c6bcea47"),
"word" : "der Apfel",
"timeStamp" : ISODate("2020-10-07T09:04:47.403Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84b9c1842471c6bcea49"),
"word" : "das Maedchen",
"timeStamp" : ISODate("2020-10-07T09:04:57.388Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84c8c1842471c6bcea4b"),
"word" : "das Auto",
"timeStamp" : ISODate("2020-10-07T09:05:12.036Z"),
"frequency" : 0,
"status" : 0
}
],
"verbs" : [],
"adjectives" : [],
"others" : [],
"salt" : "*****",
"hash" : "*****",
"__v" : 5
}
figured it out after hours
const ObjectId = require('mongodb').objectID
db.collections.users.updateOne(
{},
{$set: {"nouns.$[element].status": 3}},
{multi: true,
arrayFilters: [{"element._id":
ObjectId(req.body.inputId)}]}
);
I am trying to read some key-value from one object using Javascript but one key value is not reading at all. I am explaining my code below.
customer={
"_id" : ObjectId("5e21bdb921a1de5a8885c368"),
"IsActive" : true,
"GroupName" : "ashok",
"CustomerId" : "7008980097Saikantassss#okedqart",
"GroupCode" : "ashokgrp",
"GroupType" : "Group",
"GroupDescription" : "test description",
"GroupImage" : "",
"StoreCode" : "DKWF",
"GroupID" : "1673e78b-8d35-4c5b-9bda-35d8788a64ad",
"CreatedAt" : ISODate("2020-01-17T13:59:21.373Z"),
"UpdatedAt" : ISODate("2020-01-17T13:59:21.373Z"),
"__v" : 0
}
Here I have the above fetched value from mongodb but when I am printing the customerId value like below.
console.log(customer['CustomerId']);
//undefined
The above value is coming undefined but same time console.log(customer['GroupCode']); giving the value as ashokgrp. Here I need to print also customer['CustomerId'] value.
var customer={
"_id" : "5e21bdb921a1de5a8885c368",
"IsActive" : true,
"GroupName" : "ashok",
"CustomerId" : "7008980097Saikantassss#okedqart",
"GroupCode" : "ashokgrp",
"GroupType" : "Group",
"GroupDescription" : "test description",
"GroupImage" : "",
"StoreCode" : "DKWF",
"GroupID" : "1673e78b-8d35-4c5b-9bda-35d8788a64ad",
"CreatedAt" : "2020-01-17T13:59:21.373Z",
"UpdatedAt" : "2020-01-17T13:59:21.373Z",
"__v" : 0
}
console.log(customer.CustomerId);
It Will work .
My current doc is like this
{
"_id" : ObjectId("55ece69df332eb0000d34e12"),
"parent" : "P1",
"hierarchy" : {},
"hidden" : false,
"type" : "xyz",
"name" : "Mike",
"code" : "M110",
"date" : ISODate("2015-09-07T01:21:33.965Z"),
"__v" : 3,
"job_id" : "ca50fdf0-6904-11e6-b9af-1b0ea5d7f792"
}
now i want to have job_id as array instead. So i changed the field type to array in model schema. Now when I try to update the existing docs with some changes.
Document before saving looks like this
{
"_id" : ObjectId("55ece69df332eb0000d34e12"),
"parent" : "P1",
"hierarchy" : {},
"hidden" : false,
"type" : "xyz",
"name" : "Mike",
"code" : "M110",
"date" : ISODate("2015-09-07T01:21:33.965Z"),
"__v" : 3,
"job_id" : ["ca50fdf0-6904-11e6-b9af-1b0ea5d7f792",
"f1f04a95-42fa-41e5-a2c6-89c52c9c63f2"
]
}
so when i call model.save() method i'm getting following error:
{ [MongoError: The field 'job_id' must be an array but is of type String in document {_id: ObjectId('55ece69df332eb0000d34e12')}]
name: 'MongoError',
code: 16837,
err: 'The field \'job_id\' must be an array but is of type String in document {_id: ObjectId(\'55ece69df332eb0000d34e12\')}' }
What is the best way to handle this??
I'm using a model tree structure for my collection. As references I'm using parent-fields. I need to get attributes from the current object and all its parents. The last element in a path has a field 'target'. So I start with
var result = parent = Articles.findOne({target: this.params._id});
do {
parent = Articles.findOne({_id: parent.parent}).parent;
for (var attrname in parent) { result[attrname] = parent[attrname]; }
}
while (parent.parent === null);
That seems to be very inefficient to me. Isn't it possible to do that with one line to get an object with all elements? Then I could process that object.
Example documents
{
"_id" : "LD6h5ZcDuJjexfKfx",
"title" : "title",
"publisher" : "public",
"author" : "author"
}
{
"_id" : "KSiyh8zHRq8RZQ2E6",
"edition" : "edition",
"year" : "2020",
"parent" : "LD6h5ZcDuJjexfKfx"
}
{
"_id" : "5yCk4y25wrLBLZhyY",
"pageNumbers" : "1-10",
"target" : "9sjhzPhyTuQ5Kbh6v",
"parent" : "KSiyh8zHRq8RZQ2E6"
}
So starting with "target" : "9sjhzPhyTuQ5Kbh6v" I would like to get the two parent documents (in this example).
At least I need the dataset
"title" : "title",
"publisher" : "public",
"author" : "author",
"edition" : "edition",
"year" : "2020",
"pageNumbers" : "1-10"
If you want to do this in a single query then you need to follow the array of ancestors pattern in Mongodb. Otherwise you need to recursively traverse the branches above the leaf node as you are doing. For hierarchies with low depth such as yours this is not a big penalty.
With an array of ancestors your doc tree would look like:
{
"_id" : "LD6h5ZcDuJjexfKfx",
"title" : "title",
"publisher" : "public",
"author" : "author",
}
{
"_id" : "KSiyh8zHRq8RZQ2E6",
"edition" : "edition",
"year" : "2020",
"ancestors" : ["LD6h5ZcDuJjexfKfx"],
"parent" : "LD6h5ZcDuJjexfKfx"
}
{
"_id" : "5yCk4y25wrLBLZhyY",
"pageNumbers" : "1-10",
"target" : "9sjhzPhyTuQ5Kbh6v",
"ancestors" : ["LD6h5ZcDuJjexfKfx","KSiyh8zHRq8RZQ2E6"],
"parent" : "KSiyh8zHRq8RZQ2E6"
}
To get the doc and its parents:
Articles.find({ $or: [ { target: target },
_id: { $in: Articles.findOne({ target: target }).ancestors }]});
I'm trying to combine 3 collections into one
the first collection is make up of vehicles
Vehicle
{
"_id" : ,
"vehicle_id" : ,
"engine_id" : ,
"service_schedule_id" :
}
The other two are service schedules and parts
Service_Schedule
{
"service_schedule_id" : ,
"date" : ,
"description" :
}
Parts
{
"part_id" : ,
"vehicle_id" : ,
"description" :,
"name" :
}
What I want is to combine them all so in the end I have one collection that instead of having the id's contains the actual information from the collection
Vehicle_Complete
{
"_id" : ,
"vehicle_id" : ,
"engine_id" : ,
"service_schedule" :
{
"service_schedule_id" : ,
"date" : ,
"description" :,
"parts" :
},
"parts" :
[
{
"part_id" : ,
"description" :,
"name" :
}
]
}
I've seen some similar questions that use mapreduce but nothing so far has worked for me.