Array of Custom Objects MongoDB Schema - javascript

I need to create an array of objects with two fields (no methods needed) in mongoDB so that the document has a field that is an array of the these objects with two fields. I have no idea what the schema syntax should be however. How would I go about this?
Also:
Can I just declare an document with an array and fill it in with javascript objects created at run time?
Or should I declare the custom object in the Schema for the array holding document?
Thanks so much!

The following is an example creating an object with an array of object, each with 2 fields. Is this what you are looking for?
$ mongo
MongoDB shell version: 2.6.3
connecting to: test
>
>
> db.test.insert({myArray: [{a: 1, b: 2}, {a: 3, b:4}]})
WriteResult({ "nInserted" : 1 })
> db.test.findOne()
{
"_id" : ObjectId("53adc9301e7d2620fc75f8c7"),
"myArray" : [
{
"a" : 1,
"b" : 2
},
{
"a" : 3,
"b" : 4
}
]
}

Related

Mongoose update specific fields in entire array of objects

In a mongoose document I have a array of objects, something like this :
{
name : 'helloWorld',
arr : [
{ a : 'id1', b : 'sampleValue1', c: 'sampleValue2'},
{ a : 'id2', b: 'tempValue1', c:'tempValue2'}
]
}
In the array of objects 'arr' I want to update all the values of field 'b' and 'c' with specific values, how can I do that elegantly?
I know for a single element of the array I can do (it works) :
Model.updateOne(
{
name : 'helloWorld;,
'arr.a' : 'id1',
},
{
'arr.$.b' : 'newB',
'arr.$.c' : 'newC',
}
);
But how to do it elegantly for the entire array ?
I know I can do it using multiple queries via forEach looping for each of the 'arr.a' field, but I want an elegant preferable single query method for this.

Mongoose update inner field

I have this kind of documents in my mongoDB :
{
id: my_id
inner_foo : [
{
inner_id : id_A
inner_field : field_A
},
{
inner_id : id_B
inner_field : field_B
}
]
}
When receiving a request, i got two ids, the id one (here my_id), and the inner_id one (here for example id_A).
How can I, using JS and mongoose, update an inner field ? such as the inner_field field of one of the array contained objet using its inner_id
I think I cannot use findByIdAndUpdate since I can't make a direct reference to the correct inner_foo entry using that method, so how should I do it ?
Many thanks !
Kev.
Demo - https://mongoplayground.net/p/2pW4UrcVFYr
Read - https://docs.mongodb.com/manual/reference/operator/update/positional/
db.collection.update(
{ id: "my_id", "inner_foo.inner_id": "id_A" }, // find the matching document
{ $set: { "inner_foo.$.inner_field": "id_A_Update" }} // set the value on the matched array index
)

MongoDb Find Collections based on _id and a key in an array

So if I had something like this:
{
_id:'123',
parts: ['One','Two','Three']
}
So if I wanted parts[0], is it possible to do the find for just that?
So something like:
db.stories.find({_id:'123', part:{$eq:0}})
I know the above is wrong, but I'm wondering if it's more efficient to do the find properly if possibly (criteria related to object/array key), or simply do the broad find and go from there (i.e. use the criteria without object/document.
You can use $project and $arrayElemAt to get the first element in the array
db.stories.aggregate([
{
$match: {_id: '123'}
},{
$project: {part: {$arrayElemAt: ['$parts',0]}}
}
])
If you want to get 0 index element from the parts array you can write in this way
db.sample.find({ _id : "123" } , { parts : { $slice : [0 , 1] } } )

How can I change an array of documents to an array of values in MongoDB shell?

So, basically, I have this array of IDs:
> arrayDeptID
[
{
"departamento_id" : 0
},
{
"departamento_id" : 2
},
{
"departamento_id" : 5
},
{
"departamento_id" : 6
}
]
And I want to transform it to an array that contains only the values on the document field departamento_id, something like this:
[0, 2, 5, 6]
Is there any way to do it in MongoDB shell?
Use JavaScipt .map():
arrayDeptID.map(function(el) { return el.departamento_id })
Then MongoDB shell is a JavaScript REPL. So just about all ECMAScript built-in functions exist. It is built on V8, so whatever is in there is generally in here too.

execMatch only returning first result

I am trying to find a particular record (with an id of 1) and then to return only its history field. This history field is an array of objects with a timestamp property. When I return this history field, I want it to contain only objects with timestamp properties greater than 0.
Sample collection
[{
"_id" : 1,
"history" : [
{
"content" : "hello",
"timestamp" : 1394639953878,
"_id" : ObjectId("53208451767743b748ddbd7d")
},
{
"content" : "world",
"timestamp" : 1394639953879,
"_id" : ObjectId("33208451767743b748ddbd7e")
}
]
}]
Thus, according to Mongo and Mongoose documentation, I do something like:
model.find({_id: 1})
.select({ history: { $elemMatch: { timestamp: { $gt: 0 } } } });
The issue: I understand that there will only be one result (since I select the id 1) but I am using $elemMatch to populate its history field with all objects that have a timestamp greater than 0. The issue is that only one object is ever in history.
The $elemMatch projection returns only the first matching element satisfying the condition. Checkout the documentation.
Using aggregate would be the right approach to achieve what you want I think. Please see below:
db.bar.aggregate([
{$match:{_id:1}},
{$unwind:"$history"},
{$match:{"history.timestamp":{$gt:0}}},
{$group:{_id:"$_id", history:{$push:"$history"}}}
])

Categories

Resources