Contains Query into MongoDB Array using Mongoose - node.js

I'm trying to query into following document and want to list all document which contains TaxonomyID "1" in "TaxonomyIDs" field.
...
"Slug" : "videosecu-600tvl-outdoor-security-surveillance",
"Category" : "Digital Cameras",
"SubCategory" : "Surveillance Cameras",
"Segment" : "",
"Usabilities" : [
"Dome Cameras",
"Night Vision"
],
"TaxonomyIDs" : [
1,
12,
20,
21,
13
],
"Brand" : "VideoSecu",
...
Totally stuck!

Model.find({TaxonomyIDs: 1}, function(error, models) {
//put code to process the results here
});
mongodb interprets the query conditions above as "match any document where the TaxonomyIDs array contains 1".

Related

How to add/update in array document with condition in mongoose

I need to perform the upsert operation. Below is my document structure.
I want to update the spin_details array when there is a match found with package_id but with two conditions i.e. user_id & spin_details.package_id.
If there is a match with user_id but there is no match with spin_details.package_id then some package information has to be pushed into the spin_details array. If there is no match with user_id(only) itself then it should be able to insert a new document.
{
"_id" : ObjectId("6234ffa6bd36b0e5a05ac913"),
"user_id" : ObjectId("6230e5e2b1530b407cedeb1d"),
"__v" : 0,
"is_active" : true,
"spin_details" : [
{
"package_id" : ObjectId("6230e5e2b1530b407cedeb9d"),
"spin_count" : 10,
"_id" : ObjectId("6234ffa6f390e1fafa8e215b")
},
{
"package_id" : ObjectId("6230e5e2b1530b407cedeb2a"),
"spin_count" : 25,
"_id" : ObjectId("6234ffa6f390e1fafa8e409b")
}
]
}
I can do this using multiple different queries and then based on the result value. How can I do this with a single mongoose query for this situation?

Mongoose getting specific item in Embedded Document

I am new in NoSQL and I'm kinda stuck. Can you help me?
Is there any way to get the specific field in an array if it matches a value?
For example, I would like to get the specific item in the array accountGroup where accountGroupName=="Account 1".
I tried many codes but it just returns the whole array which has the item that matches with the value.
By the way, I am using Mongoose and Nodejs. Thanks.
//here is the database
{
"_id" : ObjectId("60d2db4b90c66c3b0832a616"),
"accountType" : "Account Type 1",
"accountGroup" : [
{
"_id" : ObjectId("60d2db5a90c66c3b0832a619"),
"accountGroupName" : "Account 1",
"rangeFrom" : 25,
"rangeTo" : 35
},
{
"_id" : ObjectId("60d3fbfbc1502c3ed8cadf86"),
"accountGroupName" : "Account2",
"rangeFrom" : 850,
"rangeTo" : 2000
},
{
"_id" : ObjectId("60d2ddb1396dbf384898fbad"),
"accountGroupName" : "account 1 sample 3",
"rangeFrom" : 10,
"rangeTo" : 15
}
],
}
{
"_id" : ObjectId("60d2db4e90c66c3b0832a617"),
"accountType" : "Account Type 2",
"accountGroup" : [
{
"_id" : ObjectId("60d2e9586c4fa82310349c7c"),
"accountGroupName" : "account 2 sample 5",
"rangeFrom" : 50,
"rangeTo" : 60
}
]
}
You can use position operator $ into projection like this:
YourModel.find({
"accountGroup.accountGroupName": "Account 1"
},
{
"accountGroup.$": 1
})
Example here
Note that you are getting the whole document because using
YourModel.find({"accountGroup.accountGroupName": "Account 1"})
You are telling mongo "Give me a document where value accountGroupName into accountGroup array is equal to Account 1. And the document who match that condition contains the whole array.
So using positional operator, is waht you need according to its description:
The positional $ operator limits the contents of an to return the first element that matches the query condition on the array.
This is why with one query you get the whole document and with the other one you get the value you want.
Also note $ return only the first subdocument that match the query.

MongoDB query with embedded document in array (3 levels)

I had this data on my MongoDB database and I would like to get only the second array about blades.
{
"_id" : ObjectId("..."),
"name" : "Westereems",
"country" : "Netherlands",
"turbines" : [
{
"turbine_id" : ObjectId("..."),
"blades" : [
{
"blade_id" : ObjectId("..."),
"position" : 2,
"size" : 50,
}
]
}
]
}
I only want one return with blade_id, position and size. I tried this query and I didn't have the expectable result:
db.collection("windfarms").find({"turbines.blades.blade_id" : ObjectId("...")}, {"turbines.blades.$" : 1, "_id" : 0})
Regards,
You can use this query, it's not an optimal query for large array's items but if you have only above items then you can use it.
you can also go with aggregation to make it more optimal.
db.collection("windfarms").find({"turbines.blades.blade_id" : ObjectId("...")}, {"turbines.blades.blade_id":1,"turbines.blades.position":1,"turbines.blades.size":1,"_id":0})

Mongodb aggregate project string as number

I have a mongo script which retrieves a value from an array and creates a new document. However, the value which it retrieves is a string. I need the value to be added to the new document as a number instead of a string because it is read by a graphing engine which ignores the value if it is a string.
From the script below, it is "value": {$arrayElemAt: ["$accountBalances", 1]} which needs to be a number instead of a string. Thanks.
db.std_sourceBusinessData.aggregate(
{ $match : {objectType: "Account Balances"}},
{ $project: {_id: 1,entity_ID: 1,objectOrigin: 1,accountBalances: 1}},
{ $unwind: "$accountBalances" },
{ $match: {"accountBalances": "Sales"}}
,
{$project: {
_id: 1
, "value": {$arrayElemAt: ["$accountBalances", 1]}
,"key": {$literal: "sales"}
,"company": "$entity_ID"
,"objectOrigin" : "$objectOrigin"
}}
,{$out: "entity_datapoints"}
)
This is what I currently get:
{
"_id" : ObjectId("5670961f910e1f54662c1d9d"),
"objectOrigin" : "Xero",
"Value" : "500.00",
"key" : "grossprofit",
"company" : "e56e09ef-5c7c-423e-b699-21469bd2ea00"
}
what I want is:
{
"_id" : ObjectId("5670961f910e1f54662c1d9d"),
"objectOrigin" : "Xero",
"Value" : 500.0000000000000,
"key" : "grossprofit",
"company" : "e56e09ef-5c7c-423e-b699-21469bd2ea00"
}

In MongoDB Not able to find sub-documents based on IDs

I'm using MongoDb (as part of MongoJS) in Node. I using subdocuments and allocating IDs to the sub-docs also.
when I do a query based on the main documents it returns me the whole document, but when I try to find the sub-document based on its ID it do't return me any result. In mongoose I have declared a seperate schema for results field having its own ID.
It is to note that I am using arrays within arrays, for the result field.
Following is the console output of this scenario.
>db.tests.find({"_id":ObjectId("56563e92c8be03ec1a341374")}).pretty();
"_id" : ObjectId("56563e92c8be03ec1a341374"),
"test" : 2,
"startAt" : ISODate("2015-11-25T23:04:50Z"),
"endedAt" : ISODate("2015-11-25T23:04:50Z"),
"results" : [
{
"_id" : ObjectId("56563e92c8be03ec1a341375"),
"second" : [
{
"sec" : 50,
"avg" : 40.6,
"grt" : 1.2
}
]
}
],
>db.tests.find({"_id":ObjectId("56563e92c8be03ec1a341375")}).pretty();
>
You cannot search for subdocuments only by their ID in mongoDb. You have to always start from the main document i.e...search for the document that has an "results" array that contains the subdocument you are looking for:
db.test.find({ "results._id" : ObjectId("56563e92c8be03ec1a341375") });
if you want the output document to contain only the subdocument you were looking for (excluding other subdocuments it the array) you can use projection {"results.$":1}:
db.test.find({ "results._id" : ObjectId("56563e92c8be03ec1a341375") },{"results.$" : 1});
It will give you this output:
{
"_id": ObjectId("56563e92c8be03ec1a341374"),
"results": [{
"_id": ObjectId("56563e92c8be03ec1a341375"),
"second": [{
"sec": 50,
"avg": 40.6,
"grt": 1.2
}]
}]
}

Resources