make one array of multiple arrays in javascript with mongodb - javascript

i have this structure in my mongodb
{
category:['A','B'],
info:.....,
}
{
category:['A','F','T'],
info:.....,
}
{
category:['A','C'],
info:.....,
}
{
category:['D','B'],
info:.....,
}
i have to query all categories,
var db = mongo.db(read+"#127.0.0.1:27017/database",{safe:false});
db.collection('comercio').find({},{_id:0,'category.$':1},function(err, result_array)
first question, there is any way to get all categories?? an other aproach instead of mine??
second question....
i have to make an array that contains all categories but not repeat any category... in this example i have to make an array that contains this...
all_categories=['A','B','C','D','F','T'];
thank you all again...

You must use Aggregation framework for this query, like this:
db.comercio.aggregate(
{ $unwind : "$category" }
);
After unwind you can use other aggregations (e.g. group) to get what you need.

You don't need aggregation framework to get back an array of distinct categories.
Just use distinct:
> db.comercio.distinct("category");
["A","B","C","D","F","T"]

Related

How to insert an Array in Node js and MongoDB

Well, I am stuck since a long time on how to treat properly an array in Node js in order to persist it in my mongobd database.
I tried a lot of stuff, i am feeling close to success, but still stuck with it with the var filmDataSchema and the var film syntax.
I really need a little help, please:
Are you using mongoose? it's an elegant mongodb object modeling for node.js and has a really nice interface to handle arrays so let's say you have a student model with grades array and you want to add a new grade, you can use the '$push' (if) or $addToSet operators like so
StudentModel.update(
{ _id: student._id },
{ $addToSet: { grades: grade } }
);
StudentModel.update(
{ _id: student._id },
{ $push: { grades: grade } }
);
use $addToSet if you want only unique items to be pushed into array. use $push if you just want to add the object to array whether or not the object is already there
more about mongoose can be found here https://mongoosejs.com/

Not able to use sort() inside of map function

The documents in my couchdb look like this:
{
docType: "event",
tags: ["bb","aa","cc"],
...
}
I would like my couchdb view function, to emit a sorted array of tags, so I tried:
function(doc) {
if (doc.docType == 'event') {
if (doc.tags.length > 0) {
emit(doc.tags.sort(), doc._id);
}
}
}
But this (.sort()) is not working as expected: The result shows only documents, where the tags array has only one entity (tags.length = 1).
I found the answer by the help of the couchDB Slack channel. sort() wants to change the positions of the elements in the original array, which is not intended by the view function. You can see exceptions of the javascript engine for each array, to be sorted and which has more than one entries. Need to switch the log level of couchdb to "debug" before.
Using the spread operator to create a new array solved the problem:
emit([...doc.tags].sort(), doc._id);

Is there a better way to check a string against the names of arrays?

I am currently trying to create a function that given the string of one variable to return the results of an array with the same name, with the intent to use this to return only the twitter profiles that are needed.
For example, if the variable profile is equal to ManUtd, then return the array ManUtd and its contents.
The array ManUtd will contain all the players on twitter who play for that club which can then be used to return only those twitter profiles.
so far my initial thought is to do something such as:
var ManUtd = [
// array containing all ManUtd twitter players
]
function checkTeam(profile){
if ( profile == ManUtd ){
// use the array ManUtd
} else if {
// the rest of the possible results
}
This isn't very efficient and seems rather verbose a solution. Is there a better way to achieve these results?
Don't make global variables called, eg, ManUtd. Instead make an object that contains keys and the values you want:
var teams = {
'ManUtd': [the array you mentioned],
'Arsenal': [some other array],
//etc
};
Then get the arrays like this:
function checkTeam(profile){
if (teams[profile]) {
return teams[profile];
}
}
Yes, there is a better way. Use a dictionary. Store all your array in the dictionary, and retrieve the right one later with the key.
See https://docs.python.org/3.5/library/stdtypes.html?highlight=dictionary#mapping-types-dict

Updating MongoDB array from variable array in batch operation?

I am working in Node.js and am attempting to push or pull the contents of an array to my mongodb collection. Currently my [working] code to pull objects from the array in FieldArray looks something like this:
for (var i=0; i < MyList.length; i++) {
collection.update(
{field:"MyValue"},
{$pull: {FieldArray: MyList[i]}},
function(err, item){...}
);
}
I'm aware of the ability to use $push/$each, $addToSet/$each and $pullall but they don't seem to accept values dynamically from an array (or I haven't found any indication that it can). Basically, I'd like to be able to use this function with an array of one item or one hundred, using the appropriate batch calls.
Is there any way to make such a call without having to loop through a separate call on the database for each iteration?
You want $pullAll. It does exactly what you are trying to iterate over
collection.update(
{ "field": "MyValue" },
{ "$pullAll": { "FieldArray": MyList } }
)
If that doesn't work then then your array elements are not matching the structure used in your document. Make them that way.

Nodejs: How to search for a substring within an array in javascript?

Assuming that I have an array that looks like the one below:
["file1.java", "file32.js", "file44.java", "file4.html", "file15.js"]
I would like to filter out only the elements that end in ".java". Therefore I would like to somehow be able to search for the substring ".java" as I'm iterating through each element in my array. How do I go about doing this? Thank you
You can use the filter() method of the Array type:
var files = ["file1.java", "file32.js", "file44.java", "file4.html", "file15.js"];
var filtered = files.filter(function(item) {
return item.endsWith(".java");
}
);
console.log(filtered);

Categories

Resources