Iterating Through an Array of Strings, Fetched from Mongodb

Iterating through an array of strings, fetched from MongoDB

Here you can check out how a framework dev explained handling this situation. MongoKitten closed issue 27

here are some quotes from his explanation incase the link becomes invalid.

"MongoKitten BSON library always returns an enum (Value) when subscripting a document."

"A BSON array is really just a document with keys from 0 to x, so the enum case for array has a document as it's associated value. Because Value can also be, say, a double or a date, it doesn't conform to the Sequence protocol.

The easiest way to iterate over the array is by using the document convenience accessor on Value. This returns the underlying document if Value is either an array or document, or an empty document if it's something else. You can then iterate like this:"

for (key, val) in doc["vals"].document {
print("Value is \(val)")
}

Display an iteration over a mongodb array

Template helpers can return arrays, so you need only fetch the object and return its myField array:

Template.myTemplate.helpers({
someHelper: function() {
var doc = MyCollection.findOne();
return doc && doc.myField;
}
});

looping through array document in mongodb

well, I don't have any experience with mongoDB, but here's an example of how to loop through each element of an object:
(I understood that your problem is the loop, if not, please tell me)

var user ={ "cartItems": [      {      "productID": "2ae6b8013ade44ac60de872f",      "quantity": 5    },     {      "productID": "1ae2b8013ade32ac60de872d",      "quantity": 5    },    {      "productID": "6ae9b8023ade44ac60de8732",      "quantity": 5    },     {      "productID": "3ae9b96d3ade43ac60de8734",      "quantity": 5    }]}
var cartItems = user.cartItems;for (var item of cartItems){ let id = item.productID; console.log("Id: " + id);}

Retrieve only the queried element in an object array in MongoDB collection

MongoDB 2.2's new $elemMatch projection operator provides another way to alter the returned document to contain only the first matched shapes element:

db.test.find(
{"shapes.color": "red"},
{_id: 0, shapes: {$elemMatch: {color: "red"}}});

Returns:

{"shapes" : [{"shape": "circle", "color": "red"}]}

In 2.2 you can also do this using the $ projection operator, where the $ in a projection object field name represents the index of the field's first matching array element from the query. The following returns the same results as above:

db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});

MongoDB 3.2 Update

Starting with the 3.2 release, you can use the new $filter aggregation operator to filter an array during projection, which has the benefit of including all matches, instead of just the first one.

db.test.aggregate([
// Get just the docs that contain a shapes element where color is 'red'
{$match: {'shapes.color': 'red'}},
{$project: {
shapes: {$filter: {
input: '$shapes',
as: 'shape',
cond: {$eq: ['$$shape.color', 'red']}
}},
_id: 0
}}
])

Results:

[ 
{
"shapes" : [
{
"shape" : "circle",
"color" : "red"
}
]
}
]

Mongodb - match all items in array of strings field

Query

  • i think you want colors to be subset of the query

Playmongo

aggregate(
[{"$match": {"$expr": {"$setIsSubset": ["$colors", ["red", "blue"]]}}}])

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in the year 1975, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Meteor: show each item from an array from mongo in separate list tag

Courses.find(); returns a cursor and not an array. Use fetch() method instead:

Template.modalAddCollaborators.helpers({
'addedCollaborators': function () {
return Courses.find().fetch();
}
});

In your template, create nested {{#each}} blocks with the first one iterating over the courses array and the next each block getting the canEditCourse array as the parameter. Inside the block, you can use this to reference the element being iterated over, something like the following for example:

<template name="modalAddCollaborators">
{{#each addedCollaborators}}
<h1>{{title}}</h1>
<ul class="list-group">
{{#each canEditCourse}}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
{{/each}}
</template>


Related Topics



Leave a reply



Submit