$each not working in mongodb - mongodb

I would like to add new data into a child element of a field in mongodb using update query with $push and $each, But it directly insert the whole part of each operator. please help me to fix it. My query given below.
> db.Groups.insert({ "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2"), "_creator" : ObjectId("55b2932cb57f47c0be6f071f"), "_messages" : ["hi"], "_inactive" : [ ], "_active" : [ Obje
> .Groups.update({ "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2")},{$push: {_active : { $each: [ ObjectId("55b2932cb57f47c0be6f072f"), ObjectId("55b2932cb57f47c0be6f073f") ]}}});
Result after running these queries
{ "__v" : 39, "_active" : [ ObjectId("55b2932cb57f47c0be6f071f"), ObjectId("55b28b203a6b52e9b90e3cd4"), { "$each" : [ ObjectId("55b2932cb57f47c0be6f072f"), ObjectId("55b2932cb57f47c0be6f073f") ] } ], "_creator" : ObjectId("55b2932cb57f47c0be6f071f"), "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2"), "_inactive" : [ ], "_messages" : [ "hi" ] }
Expected result
{ "__v" : 39, "_active" : [ ObjectId("55b2932cb57f47c0be6f071f"), ObjectId("55b28b203a6b52e9b90e3cd4"), ObjectId("55b2932cb57f47c0be6f072f"), ObjectId("55b2932cb57f47c0be6f073f") ], "_creator" : ObjectId("55b2932cb57f47c0be6f071f"), "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2"), "_inactive" : [ ], "_messages" : [ "hi" ] }

The version of MongoDB here must be a very old version, and now confirmed as 2.0.4. This should even error in 2.2.x versions due to it interpretting the $each as a field and rejecting it due to the reserved $ in the field name.
Use at least MongoDB 2.4 if you intend to use $each, otherwise there is $pushAll, which is now considered deprecated. The only difference being between 2.4 and 2.6 is that earlier than 2.6 you need to combine this with the $sort modifer as well.

Related

Mongodb Search nested array elements

I have a below data. Would like to search aclpermissions where any of the elements (CRT, READ, DLT, UPD) will match to an array of inputs.
Below query
db.AMSAppACL.find({"aclpermissions.READ" : {'$in': ['58dc0bea0cd182789fc62fab']}}).pretty();
only searches READ element. Is there any way to search all the elements instead of using or queries and aggregate
{
"_id" : ObjectId("5900d6abb9eb284a78f5a350"),
"_class" : "com.debopam.amsapp.model.AMSAppACL",
"attrUniqueCode" : "USER",
"attributeVersion" : 1,
"aclpermissions" : {
"CRT" : [
"58dc0bd70cd182789fc62faa"
],
"READ" : [
"58dc0bd70cd182789fc62faa",
"58dc0bea0cd182789fc62fab"
],
"UPD" : [
"58dc0bd70cd182789fc62faa"
],
"DLT" : [
"58dc0bd70cd182789fc62faa"
]
},
"orgHierachyIdentifier" : "14",
"orgid" : 14,
"createDate" : ISODate("2017-04-26T17:19:39.026Z"),
"lastModifiedDate" : ISODate("2017-04-26T17:19:39.026Z"),
"createdBy" : "appadmin",
"lastModifiedBy" : "appadmin"
}
You should try updating aclpermissions part of schema from dynamic keys to labeled keys.
"aclpermissions":
[
{k:"CRT", v: ["58dc0bd70cd182789fc62faa"]},
{k:"READ", v: [ "58dc0bd70cd182789fc62faa", "58dc0bea0cd182789fc62fab"]}....
]
Now you can update the query from post to something like
db.AMSAppACL.find({"aclpermissions.v" : {'$in': ['58dc0bea0cd182789fc62fab']}}).pretty();

How to count and paginate subdocument which is an object in mongodb

I have data saved in the following:
{
"_id" : ObjectId("57723b5e009793e8f3cfd1d7"),
"room" : "1003",
"inout" : {
"1" : [
"i1654",
"o1656",
"i1706",
"o1707",
],
"2" : [
"i1655",
"o1656",
"i1715",
"o1715"
],
"3" : [
"i1801"
]
}
}
how to count and paginate the subdocument "inout" which is an object?
thanks!!!
Actually, there is a small modification required in your JSON. The "inout" should be an array to use the below solution.
"$unwind" can be used here.
Modified JSON to define "inout" as array rather than Object:-
db.rooms_second.insertOne({
"_id" : ObjectId("57723b5e009793e8f3cfd1d7"),
"room" : "1003",
"inout" : [
{"1" : [
"i1654",
"o1656",
"i1706",
"o1707",
]},
{"2" : [
"i1655",
"o1656",
"i1715",
"o1715"
]},
{"3" : [
"i1801"
]}
]
});
Mongodb Query:-
In the resultset, the below query will give you one record for each element in the "inout" array.
db.rooms_second.aggregate([ { $unwind: "$inout" } ])
The pagination can be done based on the driver and API that you are using (i.e. MongoDB Java Driver etc.).

mongodb filtering the first subarray in several documents

I have the various documents mongodb like this.
this is the document.
{
"_id" : 22,
"stock" : [
{
"id" : "41u",
"qty" : 10,
"price":12
},
{
"id" : "65u",
"qty" : 14,
"price":37
}
]
}
{
"_id" : 52,
"stock" : [
{
"id" : "34u",
"qty" : 10,
"price":33
},
{
"id" : "89u",
"qty" : 14,
"price":96
}
]
}
In all documents I need to find the minimum element . Therefore , you must be:
{
"_id" : 22,
"stock" : [
{
"id" : "41u",
"qty" : 10,
"price":12
}
]
}
{
"_id" : 52,
"stock" : [
{
"id" : "34u",
"qty" : 10,
"price":33
}
]
}
I am again with mongodb
mongodb in the documentation I found examples of mapreduce ,
I welcome your comments
First of all I want to tell you, map reduce jobs are for distributed systems & large dataset. According to MongoDB's documentation:
For most aggregation operations, the Aggregation Pipeline provides
better performance and more coherent interface. However, map-reduce
operations provide some flexibility that is not presently available in
the aggregation pipeline.
Since you are not applying complex functions and I am assuming you are not making a cluster or in other words in distributed system, you can use Aggregation Framework (correct me if my assumption is wrong).
Now coming to your question, please check this similar question.

Mongodb + Mongoose: trying to add a sub-sub-item

Does this makes any sense when trying to add a sub-sub-item? (I'm new to mongo - be merciful :-))
question = db.questions.findOne({_id: ObjectId("529c5d44211c9a8c11000006")})
question.answers[0].votes.insert(...)
When I run this from the mongo console the result is an error saying [object object] does not have the method insert.
I have the following mongoDB Question Schema.
{
"__v" : 2,
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d44211c9a8c11000006"),
"answers" : [
{
"postDate" : ISODate("2013-12-02T10:14:19.060Z"),
"postDateText" : "15min ago",
"authorEmail" : "guys#pix.com",
"authorName" : "guys#pix.com",
"body" : "You need magic powder",
"isWinner" : false,
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d7b211c9a8c11000008"),
"votes" : [
{
"voteType" : "up",
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d5b211c9a8c11000007")
}
]
}
],
"authorEmail" : "guys#wix.com",
"authorName" : "guys#wix.com",
"body" : "I'm trying to fly...\n\n<pre class=\"brush: js;\">\nfunction logName(name) {\n console.log(name);\n}\n</pre>",
"isResolved" : false,
"postDate" : ISODate("2013-12-02T10:13:24.235Z"),
"tags" : [
"fly"
],
"title" : "How do I fly?",
"views" : [],
"votes" : [
{
"voteType" : "up",
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d5b211c9a8c11000007")
}
]
}
I'm trying, given a questionId and an answerId to add a vote to the votes array (which is inside the answer). I can't seem to do it. Help?
insert is for adding whole new documents; when you just want to add a new element to an array field of an existing document, you can use update along with an operator like $push.
So, in the shell you would use something like this:
db.questions.update(
{_id: ObjectId("529c5d44211c9a8c11000006")},
{'answers.0.votes': {$push: voteToPush}})

Push and slice multiple times in MongoDB

I'm trying to do a push a new value to a capped array:
db.messages.insert({name:"test1"})
db.messages.update({name:"test1"}, {"$push":{"output": {"$each": ["test1"], "$slice": -10}}})
db.messages.update({name:"test1"}, {"$push":{"output": {"$each": ["test2"], "$slice": -10}}})
So, the first time I execute the update, I get what I expect:
{
"_id" : ObjectId("51d482ee7252cb3f7eb81ac1"),
"name" : "test1",
"output" : [
"test1"
]
}
But, after the second update, I get the following:
{
"_id" : ObjectId("51d482ee7252cb3f7eb81ac1"),
"name" : "test1",
"output" : [
"test1",
{
"$each" : [
"test2"
],
"$slice" : -10
}
]
}
When I expected the following:
{
"_id" : ObjectId("51d482ee7252cb3f7eb81ac1"),
"name" : "test1",
"output" : [
"test1",
"test2"
]
}
Probably I'm not understanding how to use $push with $slice, but looking at the documentation I couldn't figure out what I'm doing wrong. How can achive adding a new element to a capped array?
The behavior you observed can be reproduced in MongoDB version 2.2. Your example works as expected in MongoDB version 2.4
> db.things.insert({name:"test1"})
> db.things.update({name:"test1"}, {"$push":{"output": {"$each": ["test1"], "$slice": -10}}})
> db.things.find()
{ "_id" : ObjectId("51d489f730d17c1ffbd6ff9f"), "name" : "test1", "output" : [ "test1" ] }
> db.things.update({name:"test1"}, {"$push":{"output": {"$each": ["test2"], "$slice": -10}}})
> db.things.find()
{ "_id" : ObjectId("51d489f730d17c1ffbd6ff9f"), "name" : "test1", "output" : [ "test1", "test2" ] }
From the documentation, $each support to $push operator was added in version 2.4
http://docs.mongodb.org/manual/reference/operator/each/#op._S_each
Most likely you are using an older version of MongoDB that does not support $each with the $push operator. What version of MongoDB are you running? You can find out the version you are running by using the following command from MongoDB shell.
>db.version()
To get the latest release of MongoDB, please go to the following link.
http://www.mongodb.org/downloads