w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
update nth document in a nested array document in mongodb
Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email; > db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}}) > db.posts.find() ..., "email" : 1 },... Q2: Same goes for this include; > db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}}) > db.posts.find() ..., "num_likes" : 1 },...

Categories : Arrays

MongoDB: If document exists VS If document does not exist
The question is how you determine that "the document" exists? Usually, you'd do this using a unique id. Now MongoDB's ObjectId comes to the rescue because it contains a timestamp already. This can also be used in queries. Instead of using an integer field User_ID, you might want to consider calling the field _id and use the ObjectId data type so you get that functionality for free. > db.test.insert({"foo" : "test"}); { "_id" : ObjectId("51cb763e58bb4077aea65b3d"), "foo" : "test" } > var foo = db.test.findOne(); > foo._id.getTimestamp(); ISODate("2013-06-26T23:16:14Z")

Categories : Mongodb

extracting indivdiual bibo:Articles from RDF document
Firstly can I ask for some clarfication on your question? I think what you are asking is to split each bibo:Article entry into its own document right? As an aside note that this is not the same as splitting each first level node because RDF/XML is not a canonical serialization i.e. the same RDF may be serialized by multiple different RDF/XML documents and there is no guarantee that they will always be the first level nodes. Now to try and answer your question, there are two main ways to achieve your aim. Using SPARQL Queries Firstly issue a SELECT query to retrieve all articles instances, then for each result issue a DESCRIBE query on the article URI which will give you a new Jena Model containing only information about that URI. Note that you can change exactly how DESCRIBE queries

Categories : Java

Mongodb: Store a tree as one nested document or store one document per node?
It looks like you are going to lots of operations in different levels of nested nodes in the tree. Although MongoDB can store a structure like you describe, it is not very good at allowing you to do update at lots of nested levels. Therefore I would recommend you to store each node as it's own document, and look at where you store the parent-child relations. Remember to optimise the schema for data operations. I'd go with your "way 1" in this case. If you would not have to change the tree a lot, and you have say 1000x more read than write operations to the tree, then you could consider using "way 2" and just deal with the extra work it takes to update the nodes at a few levels deep.

Categories : Json

Get the first document using $in with mongodb
You cannot add a limit to $in but you could cheat by using the aggregation framework: db.collection.aggregate([ {$match:{serial:{$in:[list_of_serials]}}}, {$sort:{_id:-1}}, {$group:{_id:'$serial',type:{$first:'$type'},sensors:{$first:'$sensors'},id:{$first:'$_id'}}} ]); Would get a list of all first found of each type. Edit The update will get the last inserted according to the _id.

Categories : Mongodb

How to sum every fields in a sub document of MongoDB?
You have made the classical mistake to have arbitrary field names. MongoDB is "schema-free", but it doesn't mean you don't need to think about your schema. Key names should be descriptive, and in your case, f.e. "S2" does not really mean anything. In order to do most kinds of queries and operations, you will need to redesign you schema to store your data like this: _id:... Segment:[ { field: "S1", value: 1 }, { field: "S2", value: 5 }, { field: "Sn", value: 10 }, ] You can then run your query like: db.collection.aggregate( [ { $unwind: "$Segment" }, { $group: { _id: '$_id', sum: { $sum: '$Segment.value' } } } ] ); Which then results into something like this (with the only document from your question): { "result" : [ {

Categories : Mongodb

query the value of a sub document in mongodb
You can use dot notation in the projection parameter of find to do this. In the shell: db.test.find( {_id : ObjectId("5207fe359b88bfa6f90a82b0")}, {'members.5207fe359b88bfa6f90a82af': 1, _id: 0}) Returns: { "members": { "5207fe359b88bfa6f90a82af": [ "Admin", "User" ] } }

Categories : Mongodb

mongodb - one document in many collections
Try looking at the problem inside-out: Instead of having items inside categories, have the items list the categories they belong into. You'll be able to easily find all items that belong to a category (or even multiple categories), and there is no duplication nor any need to keep many instances of the same item updated. This can be very fast and efficient, especially if you index the list of categories. Check out multikey indexes.

Categories : Database

Add a value to an array in a MongoDB document
You're looking for the $push operator. $arrayValueToAdd = array ( '22' => 1 ); $collection->update( array('email' => $user['email']), array( '$push' => array( 'emailQueries' => $arrayValueToAdd ) ) );

Categories : PHP

Not able to delete document from Mongodb database with PHP
_id field is not a string in mongodb, it's an object of ObjectId class; instead of $id = (array("_id" => $_POST["id"])); you should use $id = (array("_id" => new MongoId($_POST["id"])));

Categories : PHP

Finding embedded document without _id in MongoDB
Yes, you can. Use the dot notation to specify the property of the embedded document you are looking for. Let's say you have a collection for persons with docs like this: { _id:123, name:"john", address: { Street:"any", zip:1234 } } Then you can find a person querying by an address field like this: db.persons.find("address.zip":1234, ...) Just consider that it won't give you only the embedded doc, but the entire document (person in this case)

Categories : Mongodb

mongodb update with many embedd document
When you call Save, base on your [BsonId] field driver decides what to do with this document: if document with Id does not exist in collection, it will insert this document if document with Id exists in collection, it will update this document (based on your Id). Update means it will replace all fields with the new fields from your entity Here is an example how save method works in pseudocode (the same as in C# driver): function save( doc ) { if( doc["_id"] ) { update( {_id: doc["_id"] }, doc, { upsert: true } ); } else { insert(doc); } }

Categories : Mongodb

Single qoute in MongoDB document
I had same problem before 2 days and i have solved it using below query. below is the solution for me. SELECT * FROM tags WHERE `name` = 'limit\''s' LIMIT 0 , 30 SEE HERE

Categories : PHP

how to update a mongodb document from node.js?
Change this line: ({_id:doc._id},$set:{scores:zz}); To: ({_id:doc._id}, { $set:{scores:zz}} ); This should also probably be wrapped with a callback, to catch errors: db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) //do something. });

Categories : Node Js

Can I select an array from every document in mongodb?
You may need to use the Aggregation Framework to accomplish this. Specifically, $unwind. For example: db.blogPost.aggregate( { $project: { _id : 0 , comments: 1 } }, { $unwind: "$comments" } ); Alternatively, if viable in your situation, you could just perform the concatenation of comments at the application level instead of database level, making the Mongo query simply that of over all blog posts.

Categories : Mongodb

how to add and delete a sub document in MongoDB shell?
You are looking for $set and $unset. You would use it like so: db.collection.update({name: "John"}, {$unset: {"address.street": ""}, $set: {"address.zip": 94105}}) There is not a wildcard field name matcher in MongoDB. I don't anticipate one in the future.

Categories : Mongodb

With cakephp2.3 and mongoDB how to add array in a document?
the answer to the question was: public function salvar($name,$size,$id){ $this->mongoNoSetOperator = '$push'; // fixed array data structure $susp = array( "_id" => $id, "images"=> array( array( 'id' => new MongoId(), 'name' => $name, 'size' => $size ) ) ); return $this->save($susp); } Note: Thank Garamon from github, by clear and objective answers.

Categories : Mongodb

How to push a new document in mongodb but only if it does not exist?
Use the $addToSet operator. It ensures that the value will be added if is not in the array already. Basically: exports.addContactPost = function(req, res, err) { User.findByIdAndUpdate(req.signedCookies.userid, { $addToSet: {friendRequest: req.body.friendRequest} }, function(err) { if(err) { console.log(err); return console.log('error'); } else { console.log('postsuccess'); res.json({response: true}); } }); };

Categories : Node Js

Find document with its surroundings in MongoDB
You can not do this in one query, but you will have to use three instead: // current r = db.so.findOne( { _id: 6 } ); // previous 2 db.so .find( { publishDate: { $lte: r.publishDate }, _id: { $ne: 6 } ) .sort( { publishDate: -1 } ) .limit( 2 ); // next 2 db.so .find( { publishDate: { $gte: r.publishDate }, _id: { $ne: 6 } ) .sort( { publishDate: 1 } ) .limit( 2 );

Categories : Mongodb

delete element from document in MongoDB using C#
After searching on the web for a while, i found it myself. For those who want to know my solution: for (int j = 0 ; j < idlist.Count ; j++) { var queryDeleteValue = new QueryDocument("_id", idlist[j]); var update = Update.Unset("Flash_point"); collectionInput.Update(queryVerwijderValue, update); } So, first of all, i have a query-variable that selects the right document. Then i make an update variable where i unset the element 'Flash_point'. The last step is to do the actual update (with the parameters 'queryDeleteValue' and 'update').

Categories : C#

How to remove a document referenced by an id in mongoDB from php?
"To remove a document based on its ID, you need to ensure that you pass the ID as a MongoID object rather than just a string:" Normally what the PHP manual states is true but not for you. You have changed the type of your _id to something other than an ObjectId (aka a MongoId). With this in mind you need to search by that other object which is a MongoInt32: $db->collection->remove(array('_id'=>new MongoInt32(1)))

Categories : PHP

MongoDb c# update array in document
Working sample code for appending a list of strings to an existing list of strings using a strongly-typed Push: class Event { public ObjectId Id { get; set; } public string Name { get; set; } public List<string> Participants { get; set; } } class Program { static void Main(string[] args) { MongoClient client = new MongoClient("mongodb://localhost/test"); var db = client.GetServer().GetDatabase("test"); var collection = db.GetCollection("events"); var event0 = new Event { Name = "Birthday Party", Participants = new List<string> { "Jane Fonda" } }; collection.Insert(event0); collection.Update(Query.EQ("_id", event0.Id), Update<Event>.PushAll(p => p.Participants,

Categories : C#

mongodb c# how to work with BSON document
There are a few ways, but here's one: // build some test data BsonArray dataFields = new BsonArray { new BsonDocument { { "ID" , ObjectId.GenerateNewId()}, { "NAME", "ID"}, {"TYPE", "Text"} } }; BsonDocument nested = new BsonDocument { { "name", "John Doe" }, { "fields", dataFields }, { "address", new BsonDocument { { "street", "123 Main St." }, { "city", "Madison" }, { "state", "WI" }, { "zip", 53711} } } }; // grab the address from the document, // subdocs as a BsonDocument var address = nested["address"].AsBsonDocument; Console.WriteLine(address["city"].AsString); // or, jump straight to the value ... Console.WriteLine(nested["address"]["city"].AsString); // loop through the fields array

Categories : C#

MongoDB: query array within embedded document
IMHO Block should be a separate collection with an additional attribute num_codes (and not embedded, code untested). class Video include Mongoid::Document has_many :blocks end class Block include Mongoid::Document belongs_to :video field :index field :num_codes field :codes # warning pseudo code ahead: before_save :update_codes def update_codes # set num_codes to length of codes # delete all codes belonging to this block and recreate them end end To query for empty blocks: Blocks.where(num_codes : 0). This solves requirement 1. Regarding requirement 2: As far as I know, MongoDB does not allow you to query for values at a specific index within an array (altough I might be wrong on this one). Again my suggestion would be to make

Categories : Ruby

mongodb aggregate embedded document values
Unwind only goes down one level, so you have to call as many times as many levels you have if you do it like [ { "$project" : { "text" : "$periods.tables.rows.text" , "_id" : "$_id"}}, { "$unwind" : "$text"}, { "$unwind" : "$text"}, { "$unwind" : "$text"}, { "$group" : { "_id" : "$_id" , "texts" : { "$addToSet" : "$text"}}}, { "$project" : { "_id" : 0 , "texts" : 1}} ] It will work as you expect.

Categories : Mongodb

MongoDB (NoSQL) - Can a document reference/link to itself?
You can use the same thing in MongoDB i.e. Tomatoes can be main item with say _id=1 and these items will have parent id as 1. The collection can be noted as: { { 1, "Tomatoes", null }, { 2, "Tomatoes, Raw", 1 }, { 3, "Tomatoes, Canned", 1 }, { 4, "Tomatoes, Cooked", 1 } } Note that you can keep parentid in main item as null for query purposes (as I did above) or you can just remove that column if you do not need it (and it works as MongoDB is schema free.)

Categories : Mongodb

what is the best way to create document inside collection in MongoDB
Two main considerations in data modelling for document stores: how data will grow and change over time, and the kinds of queries your application will perform. You have provided info around how data is expected to grow. Just on that basis, I would suggest option #1. { "member_id: 1" , "content_id: 10" , "activity_id: 1" } But, it is also important to understand what kind of queries you will be performing and how you intend to use this data in your application. Additional options possible are: one document per member with an array of feeds in each grouping documents by content or activity id, if that is how your application would query the data. So in summary, to come up with an optimal model, answering question 2 above is also important. PS: Option 2 in your question definite

Categories : PHP

MongoDB C# driver upserting nested document
Try with $addToSet The $addToSet operator adds a value to an array only if the value is not in the array already. If the value is in the array, $addToSet returns without modifying the array. Something else you can do is to load your CoreElement and work with it in memory. You can add Suffs and MoreStuffs to the object checking for duplicates with C#. When you are finished with the object just save it, MongoDB will replace the object in the collection with your modified object.

Categories : Mongodb

updating and quering rating in mongodb document
What you can do is use option two from above and then combine it with a cached result field. You can set up the data flow so the result field remains consistent with the rest of the document by using the filter predicate on your update. Step one is to add a new field to your schema which will be your cached rating field. This will allow you to perform your range query without having to do the dynamic division. The problem you'll run into there is that you can't atomically increment the votes_sum & votes_num fields AND in the same atomic operation set the cached rating fields. So here's what you do. 1) Atomically increment the votes_sum and votes_num fields 2) Grab the _id, votes_sum & votes_num for the updated document 3) Update the rating but, as part of the filter predic

Categories : Mongodb

Reference a Embed Document in Doctrine2 and MongoDB
The problem is that you cannot reference an Embedded Document. You can only reference a Document. Careful reading of the Data Modeling Considerations in the MongoDB documentation reveals that you have to choose between embedding and referencing. In general, use Embedded Documents when you only need to access the Embedded Document from it's master Document (one-way has-many relationship). If you need reference a Document from multiple places (it belongs to more than one document) or query the document by itself, use references. There are many questions related to the tradeoffs between referencing and embedding on SO, so here is one question with a very good answer.

Categories : PHP

mongodb performance with large array within a document
It sounds like those 510,000 employees might actually belong to a different class or entity than simply "employees managed by supervisor 5555". Call this class "A". The employees would be marked as belonging to class "A" (and possibly other classes), and 5555 would be marked as the manager of "A", but not of the individual employees. That is under the assumption that it is more likely for the manager of class "A" to change, than all 510,000 employees falling out of class "A".

Categories : Mongodb

update the mongodb embedded document with $elemMatch
As per the documentation $elemMatch can be used for projection only. But i found an example which illustrate the use of $elemMatch in conjunction with $all. Try this out. 1) I created a document in collection in the following ways: db.testColl.insert({count:0,arr:[{token:'xya'},{token:'xyb'},{token:'xyc'},{token:'xyd'},{token:'xye'}]}) 2) then i use find command without db.testColl.find() Output: { "_id" : ObjectId("52345478ef5f122b1c9c54be"), "count" : 0, "arr" : [ { "token" : "xya" }, { "token" : "xyb" }, { "token" : "xyc" }, { "token" : "xyd" }, { "token" : "xye" } ] } 3) then i run the following command sequentially: db.testColl.update({arr:{$elemMatch:{token:'xya'}}},{'$inc':{'count':1}}) db.testColl.update({arr:{$elemMatch:{token:'xyb'}}},{'$inc':{'count':1

Categories : Mongodb

MongoDB batch insert, document too large
BatchInsert takes a BSON document as its input as such it is saying that using all 40,000 at the same time is too much. You need to break them down into batches which will fit into a single BSON document.

Categories : Mongodb

spring data mongodb query document
I can't reproduce your problem, which suggests that the issue is with the values in the database and the values you're passing in to the query (i.e. they're not matching). This is not unusual when you're trying to match dates, as you need to make sure they're stored as ISODates in the database and queried using java.util.date in the query. I have a test that shows your query working, but I've made a number of assumptions about your data. My test looks like this, hopefully this will help point you in the correct direction, or if you give me more feedback I can re-create your problem more accurately. @Test public void shouldBeAbleToQuerySpringDataWithDates() throws Exception { // Setup - insert test data into the DB SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'

Categories : Java

inserting items in list in mongodb document
I found the answer, pretty foolish on my side; just have to remove extra braces {} Instead of this db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':{lis1}}}}) Use this db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':lis1}}}) i.e remove '{'after '$each' and its corresponding '}'

Categories : Mongodb

Find largest document size in MongoDB
You can use a small shell script to get this value. Note : Following will do a full table scan var max = 0; db.test.find().forEach(function(obj) { var curr = Object.bsonsize(obj); if(max < curr) { max = curr; } }) print(max);

Categories : Mongodb

create mongodb document with subdocuments atomically?
Update with upsert=true can be used to perform an atomic "insert or update" (http://docs.mongodb.org/manual/core/update/#update-operations-with-the-upsert-flag). For instance if we want to make sure a document in Front collection with specific url is inserted exactly once, we could run something like: db.Front.update( {url: 'http://example.com'}, {$set: { url: 'http://example.com'}, found: true } ) Operations on a single document in MongoDB are always atomic. If you make updates that span over multiple documents, then no atomicity is guaranteed. In such cases, you can ask yourself: do I really need the operations to be atomic? If the answer is no, then you probably will find your way around working with potentially unconsistent data. If the answer is yes and y

Categories : Node Js

How to Update a Document in MongoDB w/Java Driver
I think your problem is here: criteriaObject.append( "_id", "ObjectId("520a56b730047339c26ec1fa")"); Should be: criteriaObject.append( "_id", new ObjectId("520a56b730047339c26ec1fa"); That way the field value is treated as an object id, not as string (containing the literal "ObjectId")

Categories : Java

MongoDB data modeling: Document embedding dilemma
If you think there might be any chance you would need get a total count grouped by X, then stick with the 2nd method. Furthermore, if there is a chance you might need it grouped by Y, that's not a bad practice to denormalize your data and store Xs embedded in Ys along with Xs embedded in Ys. That is because mongo's poor performance with aggregating. If you are sure you would not need any type of aggregation, 1st method would be better in means of faster read/write and less disk space usage. Or if you're not completely sure, store it like this: {x: "X", y: "Y", count: 42}. Make sure you create index {x: 1, y: 1} for that. This way you still keep an option to retrieve all documents by "X" or "Y". Note that having {x: 1, y: 1} index means you dont need to create {x: 1} index for querying b

Categories : Mongodb

Implementing MongoDB style document references in XML databases
I think the simplest approach would be to do away with the ID-based association and store the publisher name and location directly in each book document. Otherwise you will still have to perform a join-like operation, which is more expensive. MarkLogic performs best when all the data you need is already in the document. This usually means duplicating data. This strategy should work fine in other XQuery databases, but I can't say exactly how optimal it would be compared to MarkLogic. MarkLogic has a very extensive whitepaper explaining its indexing system and many other details. It's an excellent resource for understanding how to design optimal queries and data. This link maintains a copy of the latest version: http://developer.marklogic.com/inside-marklogic

Categories : Mongodb



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.