Fetch a field from array MongoDB Meteor - arrays

Hi I have the following collection structure:
{
"_id" : "HZw2ktDPm6EWnGaFt",
"createdAt" : ISODate("2017-04-16T17:40:59.055Z"),
"pollName" : "",
"entryOwner" : "eHPeQPMd94MQFNXmg",
"question" : [
{
"name" : "Question 1",
"questionId" : "sdPzbn9SWjE46HtM2"
},
{
"name" : "Question 2",
"questionId" : "vpMrpbJ2LZKMLEYKe"
}
],
"sharedWith" : [
{
"id" : "jjX5EDdqMtcyQwd6h",
"name" : "person 1",
"votes" : 0
},
{
"id" : "b3Ctr6LFZMd9smd4B",
"name" : "person 2",
"votes" : 0
}
],
"voters" : [
{
"voterId" : "eHPeQPMd94MQFNXmg",
"questionId" : "vpMrpbJ2LZKMLEYKe",
"optionId" : "EKnYKXEFBWnr4hnCP",
"peopleId" : "b3Ctr6LFZMd9smd4B"
},
{
"voterId" : "eHPeQPMd94MQFNXmg",
"questionId" : "vpMrpbJ2LZKMLEYKe",
"optionId" : "EKnYKXEFBWnr4hnCP",
"peopleId" : "jjX5EDdqMtcyQwd6h"
},
{
"voterId" : "eHPeQPMd94MQFNXmg",
"questionId" : "sdPzbn9SWjE46HtM2",
"optionId" : "rjYLitibXDJjGYKM7",
"peopleId" : "b3Ctr6LFZMd9smd4B"
},
{
"voterId" : "eHPeQPMd94MQFNXmg",
"questionId" : "Q6JiaGFAi2LRHS7GQ",
"optionId" : "wFoduKp23cSYJJG9i",
"peopleId" : "b3Ctr6LFZMd9smd4B"
}
]
}
I would like to get the value of Voters.peopleId by using these values.
"voterId" : "eHPeQPMd94MQFNXmg",
"questionId" : "vpMrpbJ2LZKMLEYKe",
"optionId" : "EKnYKXEFBWnr4hnCP",
I tried this and it didnt work it returns the whole document but what i want as a return is just one field:
var getPeopleId = Polls.findOne({
_id:this.props.poll._id}, {"voters": {
$elemMatch :{voterId:Meteor.userId(),questionId:selectedQuestionId,optionId:selectedOptionId}}})
Many thanks

You've got $elemMatch in the projection (2nd param) instead of the query (1st param). You also need to project the result to only include the first match. Try:
const poll = Polls.findOne(
{
_id:this.props.poll._id,
voters: {
$elemMatch: {
voterId: Meteor.userId(),
questionId: selectedQuestionId,
optionId: selectedOptionId
}
},{
'voters.$': 1
});
// guard against missing keys or no results
const peopleId = poll && poll.voters && poll.voters.peopleId;

Related

count inner array mongoose

I want to do a count on an array. This my model
modelDetail.aggregate([
{
$group: {
_id: '$main_section.dept',
count: {$sum: 'first_array.second_array.main_data'}
}
}
], function (err, result) {
if (err) {
//next(err);
console.log(err);
} else {
console.log(JSON.stringify(result));
res.json(result);
}
});
This is bringing out 0 for all the result. Output is below
[{"_id":"design","count":0},
{"_id":"training","count":0},
{"_id":"forecast","count":0},
{"_id":"internal audit","count":0},
{"_id":"research","count":0}]
I wanted to get the count of all the data
this is my schema
var userSchema = mongoose.Schema({
main_section :{
dept : String
},
first_array :[{//
floor : String,
second_array :[{//3rd level
name : String,//4th level
date : String
}]
}]
});
this is the data in the json
{ "_id" : "5bb39baf40f87f17f01734f8",
"main_section" : {
"dept" : "design"
},
"first_array" : [{ "_id" : "5bb39baf40f87f17f01734fc", "floor" : "2nd floor" ,
"second_array" : [
{ "_id" : "5bc102f6dff41a0e844dd2b7", "name" : "Blake Tyson", "date" : "2018-10-12T00:00:00Z" },
{ "_id" : "5bc102fddff41a0e844dd2bb", "name" : "Meagan Shawn", "date" : "2018-10-12T00:00:00Z" },
{ "_id" : "5bc1044dbba8b31ed42e7408", "name" : "Stephen Stone", "date" : "2018-10-12T00:00:00Z" }
]
}]
},
{ "_id" : "5bb39baf40f87f17f01734f8",
"main_section" : {
"dept" : "training"
},
"first_array" : [{ "_id" : "5bb39baf40f87f17f01734fc", "floor" : "1st floor",
"second_array" : [
{ "_id" : "5bc102f6dff41a0e844dd2b7", "name" : "Micheal Harrison", "date" : "2018-10-12T00:00:00Z" },
{ "_id" : "5bc102fddff41a0e844dd2bb", "name" : "Favour Reality", "date" : "2018-10-12T00:00:00Z" },
{ "_id" : "5bc1044dbba8b31ed42e7108", "name" : "Gift Myers", "date" : "2018-10-12T00:00:00Z" },
{ "_id" : "5bc1044dbba8b31ed42e71a1", "name" : "Drake Hills", "date" : "2018-10-12T00:00:00Z" },
{ "_id" : "5bc1044dbba8b31ed42e74c2", "name" : "Hashtan Priest", "date" : "2018-10-12T00:00:00Z" }
]
}]
},
{ "_id" : "5b98987f08925c0f5cd86780",
"main_section" : {
"dept" : "forecast"
},
"first_array" : [{ "_id" : "5b98987f08925c0f5cd86784", "floor" : "4th floor",
"second_array" : [ ]
}]
},
{ "_id" : "5b98187f08924c0f5ad86790",
"main_section" : {
"dept" : "internal audit"
},
"first_array" : [{ "_id" : "5b98987f08925c0f5cd86784", "floor" : "4th floor",
"second_array" : [ ]
}]
},
{ "_id" : "5b98187f08924c0f5ad86790",
"main_section" : {
"dept" : "research"
},
"first_array" : [{ "_id" : "5b98987f08925c0f5cd86784", "floor" : "4th floor",
"second_array" : [ ]
}]
}
Basically what i was hoping to do is to let each of the array produces the total number of elements
in the array for second alongside with the main section so for example
design would output 3
training would output 5
forecast would output 0
internal audit would output 0
research would output 0
So, any help is greatly appreciated!

mongo query - getting a specific object (its `_id` is known) from array of object BUT this array is also a part of list of documents

how can I query to get the specific message from either inbox or outbox given that I have its _id --> i.e. message id.
this is my route
get("/getSpecificMessage/{Message_id}", (req, res) => {..}
what I can do is find all the buyer/dealer and then go through inbox/outbox of all the buyer/dealer and then find the message with _id i.e. message_id
--> can I do it better then that.
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e1"),
"address" : {
"proper_address" : "sarai kale khan",
"lat" : 28.58894,
"long" : "77.25692"
},
"name" : "prashant",
"password" : "jfalksdjlk;jasdl",
"email" : "prashant#gmail.com",
"inbox" : [
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e4"),
"date" : ISODate("2018-09-04T23:03:41.627Z"),
"from" : "1#1.com",
"message" : "message_1"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e3"),
"date" : ISODate("2018-09-04T23:03:41.627Z"),
"from" : "2#2.com",
"message" : "message_2"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e2"),
"date" : ISODate("2018-09-04T23:03:41.627Z"),
"from" : "3#3.com",
"message" : "message_3"
}
],
"outbox" : [
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e7"),
"date" : ISODate("2018-09-04T23:03:41.627Z"),
"to" : "1#1.com",
"message" : "message_4"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e6"),
"date" : ISODate("2018-09-04T23:03:41.627Z"),
"to" : "1#1.com",
"message" : "message_5"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e5"),
"date" : ISODate("2018-09-04T23:03:41.627Z"),
"to" : "1#1.com",
"message" : "message_6"
}
],
"__v" : 0
}
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e8"),
"address" : {
"proper_address" : "najafgarah",
"lat" : 28.58894,
"long" : "77.25692"
},
"name" : "rahul",
"password" : "jkalsjdflasdl",
"email" : "rahul#gmail.com",
"inbox" : [
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083eb"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"from" : "1#1.com",
"message" : "message_1"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083ea"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"from" : "2#2.com",
"message" : "message_2"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083e9"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"from" : "3#3.com",
"message" : "message_3"
}
],
"outbox" : [
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083ee"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"to" : "1#1.com",
"message" : "message_4"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083ed"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"to" : "1#1.com",
"message" : "message_5"
},
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083ec"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"to" : "1#1.com",
"message" : "message_6"
}
],
"__v" : 0
}
So if I have the _id = 5b8f0f4de276dd1e0ff083ea and I want
{
"_id" : ObjectId("5b8f0f4de276dd1e0ff083ea"),
"date" : ISODate("2018-09-04T23:03:41.639Z"),
"from" : "2#2.com",
"message" : "message_2"
}
I am not sure if you want it using MongoDB scripts or your app language (Nodejs if I am mistaken)
This is how it works on Mongo Shell Script
db.MODEL.find( { _id: DOCUMENT_ID },
{ inbox: { $elemMatch: { _id: MESSAGE_ID } } } )
Documentation is here
If this is not what you want, please update your post and add which language/framework you are using
This is what you could do using the aggregation framework:
var oId = new ObjectId("5b8f0f4de276dd1e0ff083ea");
db.collection.aggregate({
$match: { // can be skipped but I'd personally keep it because this will use an index on "input._id"/"output._id" (if there is one) to filter out irrelevant documents
$or: [
{ "inbox": { $elemMatch: { "_id": oId } } },
{ "outbox": { $elemMatch: { "_id": oId } } },
]
}
}, {
$project: {
result: {
$concatArrays: [
{ $filter: { "input": "$inbox", "cond": { $eq: [ "$$this._id", oId ] } } },
{ $filter: { "input": "$outbox", "cond": { $eq: [ "$$this._id", oId ] } } }
]
}
}
}, {
$unwind: "$result" // flatten the result array
}, {
$replaceRoot: {
"newRoot": "$result" // move "result" contents all the way up
}
})

Mongo matching only where first element of array has certain field value

I have a query below that extracts a couple of values from a large nested document. It tells me the user id and the first item name for each order.
This works fine, however I want it to only return the record where the first item's name is not null and is not blank. I can't figure out how to add a second query to the $match operator below to achieve this
db.getCollection('Orders').aggregate
([
{ $match : { "Items.1" : { $exists : true }}, ???},
{ $project: {
_id:0,
'UserId': '$User.EntityId',
'ItemName': {$arrayElemAt: ['$Items.Details.ItemName', 0]}
}
}
]);
Edited to show sample document
{
"_id" : "order-666156",
"State" : "ValidationFailed",
"LastUpdated" : {
"DateTime" : ISODate("2017-09-26T08:54:16.241Z"),
"Ticks" : NumberLong(636420128562417375)
},
"SourceOrderId" : "666156",
"User" : {
"EntityId" : NumberLong(34450),
"Name" : "Bill Baker",
"Country" : "United States",
"Region" : "North America",
"CountryISOCode" : "US",
},
"Region" : null,
"Currency" : null,
"Items" : [
{
"ClientOrderId" : "18740113",
"OrigClientOrderId" : "18740113",
"Quantity" : NumberDecimal("7487.0"),
"TransactDateTime" : {
"DateTime" : Date(-62135596800000),
"Ticks" : NumberLong(0)
},
"Text" : null,
"LocateRequired" : false,
"Details" : {
"ItemName" : "Test Item 1",
"ItemCost" : 1495.20
}
},
{
"ClientOrderId" : "18740116",
"OrigClientOrderId" : "18740116",
"Quantity" : NumberDecimal("241.0"),
"TransactDateTime" : {
"DateTime" : Date(-62135596800000),
"Ticks" : NumberLong(0)
},
"Text" : null,
"LocateRequired" : false,
"Details" : {
"ItemName" : "Test Item 2",
"ItemCost" : 2152.64
}
}
]
}
You need to add the two conditions to your existing $match (not null and not blank) to check the Items as:
$match : { "Items.1" : { $exists : true, "$ne": null,"$ne":""}
If you want to check the element Items[0].Details.ItemName you can doing using the operator $and
{ $match : {
$and: [
{"Items.1" : { $exists : true }},
{"Items.Details.ItemName" : { $ne : null}},
{"Items.Details.ItemName" : { $ne : ""}},
]
}},

mongodb ObjectId find with sails, returns all the data

in my sails controller I have implement a function to find users. but when I try to search using ObjectId it returns all the data. I couldn't find any reason. but it works when I create a new separate field as "userID", and find using "userID". I think the problem is find using the "ObjectId" what could be the issue.
module.exports = {
updateOrders : function(req,res){
var ObjectId = require('mongodb').ObjectID;
console.log("req " + req);
var data = req.body;
var obj = [];
console.log("\ndata "+(data));
var jdata = JSON.stringify(data);
console.log("\njdata: "+jdata);
data.forEach(function(orders){
var objid = ObjectId(orders.id);
console.log("Obj orders id :" + objid);
ApplicationOrder.find({id: ObjectId(orders.id)}).exec(function (err, order) {
if (err){
return done(err);
}
console.log('order ' + order);
obj.push(order);
});
})
res.send(obj);
}
};
Json data: printed in the console.
{
"_id" : ObjectId("59a8f820caf1cae37af72c0c"),
"appId" : "59a669431954a69e37c20b69",
"registeredUser" : "59a677811954a69e37c20b73",
"item" : [
{
"id" : "59a669441954a69e37c20b70",
"name" : "Short x",
"qty" : 1,
"sku" : "1111",
"totWeight" : null,
"price" : "250",
"total" : "250",
"imgURL" : [
{
"img" : "short_x.png"
}
],
"totalQty" : 218
}
],
"amount" : "250",
"customerName" : "dilakshan",
"deliverName" : "dilakshan",
"deliveryNo" : "11010",
"deliveryStreet" : "delgoda",
"deliveryCity" : "kandana",
"deliveryCountry" : "Sri Lanka",
"deliveryZip" : "11010",
"telNumber" : 94779967409,
"tax" : "0",
"shippingCost" : "0",
"shippingOpt" : "Flat Rate",
"email" : "s.dilakshan#yahoo.com",
"currency" : "$",
"paymentStatus" : "Pending",
"fulfillmentStatus" : "Pending",
"createdAt" : ISODate("2017-09-01T06:03:12.584Z"),
"updatedAt" : ISODate("2017-09-01T06:03:12.584Z")
}
{
"_id" : ObjectId("59a8f82fcaf1cae37af72c0d"),
"appId" : "59a669431954a69e37c20b69",
"registeredUser" : "59a677811954a69e37c20b73",
"item" : [
{
"id" : "59a669441954a69e37c20b6d",
"name" : "Shirt x",
"qty" : 1,
"sku" : "1111",
"totWeight" : null,
"price" : "250",
"total" : "250",
"imgURL" : [
{
"img" : "shirt_x.png"
}
],
"totalQty" : 244
}
],
"amount" : "250",
"customerName" : "dilakshan",
"deliverName" : "dilakshan",
"deliveryNo" : "11010",
"deliveryStreet" : "delgoda",
"deliveryCity" : "kandana",
"deliveryCountry" : "Sri Lanka",
"deliveryZip" : "11010",
"telNumber" : 94779967409,
"tax" : "0",
"shippingCost" : "0",
"shippingOpt" : "Flat Rate",
"email" : "s.dilakshan#yahoo.com",
"currency" : "$",
"paymentStatus" : "Pending",
"fulfillmentStatus" : "Pending",
"createdAt" : ISODate("2017-09-01T06:03:27.022Z"),
"updatedAt" : ISODate("2017-09-01T06:03:27.022Z")
}
{
"_id" : ObjectId("59a8f83ecaf1cae37af72c0e"),
"appId" : "59a669431954a69e37c20b69",
"registeredUser" : "59a677811954a69e37c20b73",
"item" : [
{
"id" : "59a669441954a69e37c20b71",
"name" : "Beach Suit",
"qty" : 2,
"sku" : "1111",
"totWeight" : null,
"price" : "250",
"total" : "250",
"imgURL" : [
{
"img" : "cloth3.png"
}
],
"totalQty" : 238
}
],
"amount" : "500",
"customerName" : "dilakshan",
"deliverName" : "dilakshan",
"deliveryNo" : "11010",
"deliveryStreet" : "delgoda",
"deliveryCity" : "kandana",
"deliveryCountry" : "Sri Lanka",
"deliveryZip" : "11010",
"telNumber" : 94779967409,
"tax" : "0",
"shippingCost" : "0",
"shippingOpt" : "Flat Rate",
"email" : "s.dilakshan#yahoo.com",
"currency" : "$",
"paymentStatus" : "Pending",
"fulfillmentStatus" : "Pending",
"createdAt" : ISODate("2017-09-01T06:03:42.439Z"),
"updatedAt" : ISODate("2017-09-01T06:03:42.439Z")
}
For standard sails.js/waterline queries, you have to use the id as a String in your query params, do not use ObjectId(ordersId).
When you use a sails native query, use ObjectId(ordersId).
If you are using any mongodb adapter then do not try to convert id by ObjectId(orders.id).Try normal query like
ApplicationOrder.find({'id':orders.id})
For native sails query,you have to convert id to objectId.
I finally was able to fix the issue. I had to edit the my model class in sails and use only orders.id model class,
_id:{type : 'objectid'} and when search
.find({_id: orders.id})
this worked for me perfectly.

Why I can't get the full document form array?

I have this document in stored in my collection:
{ "_id" : ObjectId("5707b95b8415b224a48a0b2d"),
"companyId" : ObjectId("570269639caabe24e4e4043e"),
"descriptions" : [
{ "id" : ObjectId("5707b95b8415b224a48a0b2a"), "description" : "test" },
{ "id" : ObjectId("570cd8164fff3a20f88c0dc9"), "description" : "test1" },
{ "id" : ObjectId("570ce6ba4fff3a052c8c570f"), "description" : "etr" },
{ "id" : ObjectId("570cf1b64fff3a1a14d71716"), "description" : "43" },
{ "id" : ObjectId("570cf1b64fff3a1a14d71717"), "description" : "43" },
{ "id" : ObjectId("570cf1b64fff3a1a14d71719"), "description" : "345" }
],
"options" : [
{ "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"), "description" : "test" },
{ "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"), "description" : "test1" }
]
}
Now I'm trying to get the objects from the options array that are matching the descriptionId and here is how I'm doing it
db.CustomFields.find({companyId: ObjectId("570269639caabe24e4e4043e")},{"options.descriptionId": ObjectId("5707b95b8415b224a48a0b2a")})
But the result contains only the descriptionId - the description property is missing.
here is how the result looks like:
{ "_id" : ObjectId("5707b95b8415b224a48a0b2d"),
"options" : [
{ "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a") },
{ "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a") }
]
}
Why my query is not returning the full document from the array, but only a part of it? Can you give me a push?
EDIT
This is what I'm expecting to get from the query
{ "_id" : ObjectId("5707b95b8415b224a48a0b2d"),
"options" : [
{ "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a", "description" : "test") },
{ "descriptionId" : ObjectId("5707b95b8415b224a48a0b2a", "description" : "test1") }
]
}
You need to include the other query with "options.descriptionId" together with the companyId query and use projection to return just the array you want.
The following shows this:
db.customFields.find(
{
"companyId": ObjectId("570269639caabe24e4e4043e"),
"options.descriptionId": ObjectId("5707b95b8415b224a48a0b2a")
},
{ "options": 1 }
);
Output
{
"_id" : ObjectId("5707b95b8415b224a48a0b2d"),
"options" : [
{
"descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"),
"description" : "test"
},
{
"descriptionId" : ObjectId("5707b95b8415b224a48a0b2a"),
"description" : "test1"
}
]
}
Try this
db.CustomFields.find({companyId: ObjectId("570269639caabe24e4e4043e"),"options.descriptionId": ObjectId("5707b95b8415b224a48a0b2a")})

Resources