Two arrays inside an array with mongodb/mongoose - node.js

I have the following mongodb's query:
db.history.distinct('city',{code: 'A-200-01'})
Then I get this:
[1.0, 2.0]
As you can see it's a simple array.
And i'd like to get an array with two arrays inside of it using a mongoose or mongodb's query. Something like this:
"property": [ [1.0], [2.0] ]
This is my first time using mongoose and mongodb's queries so i hope you guys could help me, that would be awesome

No need to use mongodb or mongoose for that (it is probably impossible). If you need to modify output to different format the node.js itself is most usable tool.
const original = [1.0, 2.0]
const arr = [];
original.forEach(item => arr.push([item]));
console.log({property: arr});

Related

Filter data in CouchDB as IN in MySQL

I am wondering if i could filter data in Couchdb similar with IN in MySQL. For example the map function is :
function(doc) {
emit(doc.idWord, [doc.idTwitterData, doc.tf*doc.idf]);
}
I want to select only documents that have idWord with values 1 or 5 for example. I tried to set startkey=1 and endkey=5 but it is not working.
It's very simple. All you need to query is ?keys=[1,5]. This will fetch all the records with the idWord equal to 1 or 5. You might want to encode the [ ]
As an addition: you use the parameters startkey and endkey if you are doing a ranged query. Here is a good explanation how a ranged query works.

Is it better to query MongoDB a lot or loop a large array

If I have a large array of objects/documents to be inserted to MongoDB (with Mongoose). But each object has a property that first needs to be filled. Is it faster to query MongoDB for this property for each document. Or is it better to get one big array and loop that every time.
The query and loop would be very simple and the documents queried are small. The collection (and thus the array) has about 3000 items.
At what point do Mongos indexes, native driver, etc. outweigh the overhead of the queries?
Edit:
A simple example would be.
I have an array of documents like this.
{
prop1: 'abc',
prop2: '123',
prop3: ''
}
And for the value of prop3 I need to query MongoDB to match prop1. Those documents look something like this.
{
prop1: 'abc',
prop3: 564
}
There are about 3000 of these second documents. So do I query them or loop an array
If i have understood your question correctly you want to do something as below
1) You have an array which you need to insert in db.
var array=[
{foo: "foo", bar:""},
{foo: "foo", bar:""},
{foo: "foo", bar:""}
]
2) The input array is not complete. You need to assign value to one of the property (in this case bar) in each object of the array before inserting in db.
var array=[
{foo: "foo", bar:"bar"},
{foo: "foo", bar:"bar1"},
{foo: "foo", bar:"bar2"},
]
In this situation, i would say looping the array is any day a better option than accessing data base one by one. Remember db operations are more often costly than looping.
You should do
1)
var array=[//array goes here ]
2) Loop through the array and assign value to the property
for(//iterate through array){
//assign the property value
}
3) Insert updated array in database in one go.

Compare values inside same subdocument for findOne() [MongoDB]

I have a database full of objects that look ~exactly like this (simplified for clarity):
{
"_id": "GIFT100",
"price": 100,
"priceHistory": [
100, 110
],
"update": 1444183299242
}
What I'm trying to do is create a query document for MongoJS (or MongoDB and I can figure out the rest) that looks for the fact that priceHistory[0] < priceHistory[1].
I would want my query document to return the above record as a result. Alternatively, I could change my document code to compare price < priceHistory[0] but I believe this still leads to the same problem (comparing values inside the same document).
Any help would be appreciated, I've exhausted my Google-foo.
Edit:
I want to return a set of records that indicate a price drop since our last scan (performed daily). Basically a set of "sale" items from a data source I don't control.
You can use the $where clause, but be careful--it's slow, it cannot use your indexes, and it will perform a full table scan. Pass on whatever Javascript you want to use for comparison:
db.collection.findOne({$where: "priceHistory[0] < priceHistory[1]"})
Additionally, you can skip the $where statement if that's the only thing you're querying by:
db.collection.findOne("priceHistory[0] < priceHistory[1]")

Mongodb. How to get boolean value representing existance of id in an array of ids?

I've got a model which have property
_idUserReadArr // array of users who have read an article
It is going to be a huge array.
And I want my API to return a boolean value
isRead
Which should be true if _idUserReadArr contains particular id and false in other case.
So, instead of
_idUserArr = [1, 2, 3]
I want to get isRead = true or isRead = false and do NOT return or do some manipulations directly with big _idUserReadArr array.
I'n working with node.js using mongoose.
Without using the aggregation framework, you can't change the nature of the output, but with a simple wrapper, you can come very close. In this case, using the aggregation framework really isn't necessary as this solution is simple and efficient.
When you specify the find that you need, just limit the results to a single field (like _id).
http://mongoosejs.com/docs/api.html#model_Model.find
myModel.find({ ... condition ... }, "_id", function(err, docs) {
// the existence of the doc means your condition was true
// without sending back the entire document/array structure
});
findOne also has the same functionality (as do several of the other findXYZ functions in Mongoose).
This functionality is supported by MongoDB's native support for a projection as documented here.

Mongodb: How to order a "select in" in same order as elements of the array

I'm performing this mongo query:
db.mytable.find({id:{$in:["1","2", "3", "4" ]}});
It returns all results in a strange order, as it follows:
4,3,2,1
I need to retrieve all results in same order as it was defined in the query array.
1,2,3,4
Is it possible ?
There is indeed no guarantee about the order of results returned from your query, but you could do a sort afterwards with the result. Two examples, the first one with the order you wanted, the second one reversed.
const arr = ["1", "2", "3", "4" ];
db.collection.find({ id: { $in: arr }})
.then(result => {
let sorted = arr.map(i => result.find(j => j.id === i));
console.log(sorted) // 1, 2, 3, 4
let reversed = arr.reverse().map(i => result.find(j => j.id === i));
console.log(reversed) // 4, 3, 2, 1
});
In case you want to do real MongoDB ID lookups, use db.collection.find({ _id: { $in: arr }}) and .map(i => result.find(j => j._id == i)) (Notice the two equal signs instead of three)
A couple of things to note:
1.) MongoDB, like most databases, makes no guarantees about the order of results returned from your query unless you use a call to sort(). If you really want to guarantee that your query result is returned in a a specific order, you'll need to specify that specific sort order.
2.) In general, the most recently updated/moved document will show up at the end of your result set but there are still no guarantees. MongoDB uses "natural order" for its native ordering of objects and although this is very close to the order of insertion, it is not guaranteed to be the same.
3.) Indexed fields will behave differently. It's worth pointing out that it looks like your query is using id and not _id. The former, _id would be indexed by default and id would not be indexed unless you've explicitly added an index to that field.
You can read more about MongoDB's sorting and ordering here:
http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order
you can write a query like this :
db.mytable.find({id:{$in:["1","2", "3", "4" ]}}).sort({id:1})
To have your results ORDER BY id ASC
Source : MongoDB Advanced Queries
But if you just want to order the results based on your $in array, try to sort your $in array in the reverse order, the result regarding to the first element of your $in array is likely to appear as the last element of the results

Resources