BsonDocument.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using MongoDB.Bson.IO;
  21. using MongoDB.Bson.Serialization;
  22. using MongoDB.Bson.Serialization.Serializers;
  23. using MongoDB.Shared;
  24. namespace MongoDB.Bson
  25. {
  26. /// <summary>
  27. /// Represents a BSON document.
  28. /// </summary>
  29. #if NET452
  30. [Serializable]
  31. #endif
  32. public class BsonDocument : BsonValue, IComparable<BsonDocument>, IConvertibleToBsonDocument, IEnumerable<BsonElement>, IEquatable<BsonDocument>
  33. {
  34. // constants
  35. private const int __indexesThreshold = 8; // the _indexes dictionary will not be created until the document grows to contain 8 elements
  36. // private fields
  37. // use a list and a dictionary because we want to preserve the order in which the elements were added
  38. // if duplicate names are present only the first one will be in the dictionary (the others can only be accessed by index)
  39. private readonly List<BsonElement> _elements = new List<BsonElement>();
  40. private Dictionary<string, int> _indexes = null; // maps names to indexes into elements list (not created until there are enough elements to justify it)
  41. private bool _allowDuplicateNames;
  42. // constructors
  43. /// <summary>
  44. /// Initializes a new instance of the BsonDocument class.
  45. /// </summary>
  46. public BsonDocument()
  47. {
  48. }
  49. /// <summary>
  50. /// Initializes a new instance of the BsonDocument class specifying whether duplicate element names are allowed
  51. /// (allowing duplicate element names is not recommended).
  52. /// </summary>
  53. /// <param name="allowDuplicateNames">Whether duplicate element names are allowed.</param>
  54. public BsonDocument(bool allowDuplicateNames)
  55. {
  56. _allowDuplicateNames = allowDuplicateNames;
  57. }
  58. /// <summary>
  59. /// Initializes a new instance of the BsonDocument class and adds one element.
  60. /// </summary>
  61. /// <param name="element">An element to add to the document.</param>
  62. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  63. public BsonDocument(BsonElement element)
  64. {
  65. Add(element);
  66. }
  67. /// <summary>
  68. /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
  69. /// </summary>
  70. /// <param name="dictionary">A dictionary to initialize the document from.</param>
  71. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  72. public BsonDocument(Dictionary<string, object> dictionary)
  73. {
  74. AddRange(dictionary);
  75. }
  76. /// <summary>
  77. /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
  78. /// </summary>
  79. /// <param name="dictionary">A dictionary to initialize the document from.</param>
  80. /// <param name="keys">A list of keys to select values from the dictionary.</param>
  81. [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
  82. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  83. public BsonDocument(Dictionary<string, object> dictionary, IEnumerable<string> keys)
  84. {
  85. Add(dictionary, keys);
  86. }
  87. /// <summary>
  88. /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
  89. /// </summary>
  90. /// <param name="dictionary">A dictionary to initialize the document from.</param>
  91. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  92. public BsonDocument(IEnumerable<KeyValuePair<string, object>> dictionary)
  93. {
  94. AddRange(dictionary);
  95. }
  96. /// <summary>
  97. /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
  98. /// </summary>
  99. /// <param name="dictionary">A dictionary to initialize the document from.</param>
  100. /// <param name="keys">A list of keys to select values from the dictionary.</param>
  101. [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
  102. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  103. public BsonDocument(IDictionary<string, object> dictionary, IEnumerable<string> keys)
  104. {
  105. Add(dictionary, keys);
  106. }
  107. /// <summary>
  108. /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
  109. /// </summary>
  110. /// <param name="dictionary">A dictionary to initialize the document from.</param>
  111. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  112. public BsonDocument(IDictionary dictionary)
  113. {
  114. AddRange(dictionary);
  115. }
  116. /// <summary>
  117. /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
  118. /// </summary>
  119. /// <param name="dictionary">A dictionary to initialize the document from.</param>
  120. /// <param name="keys">A list of keys to select values from the dictionary.</param>
  121. [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
  122. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  123. public BsonDocument(IDictionary dictionary, IEnumerable keys)
  124. {
  125. Add(dictionary, keys);
  126. }
  127. /// <summary>
  128. /// Initializes a new instance of the BsonDocument class and adds new elements from a list of elements.
  129. /// </summary>
  130. /// <param name="elements">A list of elements to add to the document.</param>
  131. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  132. public BsonDocument(IEnumerable<BsonElement> elements)
  133. {
  134. AddRange(elements);
  135. }
  136. /// <summary>
  137. /// Initializes a new instance of the BsonDocument class and adds one or more elements.
  138. /// </summary>
  139. /// <param name="elements">One or more elements to add to the document.</param>
  140. [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
  141. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  142. public BsonDocument(params BsonElement[] elements)
  143. {
  144. Add(elements);
  145. }
  146. /// <summary>
  147. /// Initializes a new instance of the BsonDocument class and creates and adds a new element.
  148. /// </summary>
  149. /// <param name="name">The name of the element to add to the document.</param>
  150. /// <param name="value">The value of the element to add to the document.</param>
  151. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  152. public BsonDocument(string name, BsonValue value)
  153. {
  154. Add(name, value);
  155. }
  156. // public operators
  157. /// <summary>
  158. /// Compares two BsonDocument values.
  159. /// </summary>
  160. /// <param name="lhs">The first BsonDocument.</param>
  161. /// <param name="rhs">The other BsonDocument.</param>
  162. /// <returns>True if the two BsonDocument values are not equal according to ==.</returns>
  163. public static bool operator !=(BsonDocument lhs, BsonDocument rhs)
  164. {
  165. return !(lhs == rhs);
  166. }
  167. /// <summary>
  168. /// Compares two BsonDocument values.
  169. /// </summary>
  170. /// <param name="lhs">The first BsonDocument.</param>
  171. /// <param name="rhs">The other BsonDocument.</param>
  172. /// <returns>True if the two BsonDocument values are equal according to ==.</returns>
  173. public static bool operator ==(BsonDocument lhs, BsonDocument rhs)
  174. {
  175. return object.Equals(lhs, rhs); // handles lhs == null correctly
  176. }
  177. // public properties
  178. /// <summary>
  179. /// Gets or sets whether to allow duplicate names (allowing duplicate names is not recommended).
  180. /// </summary>
  181. public bool AllowDuplicateNames
  182. {
  183. get { return _allowDuplicateNames; }
  184. set { _allowDuplicateNames = value; }
  185. }
  186. /// <summary>
  187. /// Gets the BsonType of this BsonValue.
  188. /// </summary>
  189. public override BsonType BsonType
  190. {
  191. get { return BsonType.Document; }
  192. }
  193. // ElementCount could be greater than the number of Names if allowDuplicateNames is true
  194. /// <summary>
  195. /// Gets the number of elements.
  196. /// </summary>
  197. public virtual int ElementCount
  198. {
  199. get { return _elements.Count; }
  200. }
  201. /// <summary>
  202. /// Gets the elements.
  203. /// </summary>
  204. public virtual IEnumerable<BsonElement> Elements
  205. {
  206. get { return _elements; }
  207. }
  208. /// <summary>
  209. /// Gets the element names.
  210. /// </summary>
  211. public virtual IEnumerable<string> Names
  212. {
  213. get { return _elements.Select(e => e.Name); }
  214. }
  215. /// <summary>
  216. /// Gets the raw values (see BsonValue.RawValue).
  217. /// </summary>
  218. [Obsolete("Use Values instead.")]
  219. public virtual IEnumerable<object> RawValues
  220. {
  221. get { return _elements.Select(e => e.Value.RawValue); }
  222. }
  223. /// <summary>
  224. /// Gets the values.
  225. /// </summary>
  226. public virtual IEnumerable<BsonValue> Values
  227. {
  228. get { return _elements.Select(e => e.Value); }
  229. }
  230. // public indexers
  231. // note: the return type of the indexers is BsonValue and NOT BsonElement so that we can write code like:
  232. // BsonDocument car;
  233. // car["color"] = "red"; // changes value of existing element or adds new element
  234. // note: we are using implicit conversion from string to BsonValue
  235. // to convert the returned BsonValue to a .NET type you have two approaches (explicit cast or As method):
  236. // string color = (string) car["color"]; // throws exception if value is not a string (returns null if not found)
  237. // string color = car["color"].AsString; // throws exception if value is not a string (results in a NullReferenceException if not found)
  238. // string color = car["color", "none"].AsString; // throws exception if value is not a string (default to "none" if not found)
  239. // the second approach offers a more fluent interface (with fewer parenthesis!)
  240. // string name = car["brand"].AsBsonSymbol.Name;
  241. // string name = ((BsonSymbol) car["brand"]).Name; // the extra parenthesis are required and harder to read
  242. // there are also some conversion methods (and note that ToBoolean uses the JavaScript definition of truthiness)
  243. // bool ok = result["ok"].ToBoolean(); // works whether ok is false, true, 0, 0.0, 1, 1.0, "", "xyz", BsonNull.Value, etc...
  244. // bool ok = result["ok", false].ToBoolean(); // defaults to false if ok element is not found
  245. // int n = result["n"].ToInt32(); // works whether n is Int32, Int64, Double or String (if it can be parsed)
  246. // long n = result["n"].ToInt64(); // works whether n is Int32, Int64, Double or String (if it can be parsed)
  247. // double d = result["n"].ToDouble(); // works whether d is Int32, Int64, Double or String (if it can be parsed)
  248. // to work in terms of BsonElements use Add, GetElement and SetElement
  249. // car.Add(new BsonElement("color", "red")); // might throw exception if allowDuplicateNames is false
  250. // car.SetElement(new BsonElement("color", "red")); // replaces existing element or adds new element
  251. // BsonElement colorElement = car.GetElement("color"); // returns null if element "color" is not found
  252. /// <summary>
  253. /// Gets or sets a value by position.
  254. /// </summary>
  255. /// <param name="index">The position.</param>
  256. /// <returns>The value.</returns>
  257. public override BsonValue this[int index]
  258. {
  259. get { return _elements[index].Value; }
  260. set
  261. {
  262. if (value == null)
  263. {
  264. throw new ArgumentNullException("value");
  265. }
  266. _elements[index] = new BsonElement(_elements[index].Name, value);
  267. }
  268. }
  269. /// <summary>
  270. /// Gets the value of an element or a default value if the element is not found.
  271. /// </summary>
  272. /// <param name="name">The name of the element.</param>
  273. /// <param name="defaultValue">The default value to return if the element is not found.</param>
  274. /// <returns>Teh value of the element or a default value if the element is not found.</returns>
  275. [Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")]
  276. public virtual BsonValue this[string name, BsonValue defaultValue]
  277. {
  278. get { return GetValue(name, defaultValue); }
  279. }
  280. /// <summary>
  281. /// Gets or sets a value by name.
  282. /// </summary>
  283. /// <param name="name">The name.</param>
  284. /// <returns>The value.</returns>
  285. public override BsonValue this[string name]
  286. {
  287. get
  288. {
  289. if (name == null)
  290. {
  291. throw new ArgumentNullException("name");
  292. }
  293. var index = IndexOfName(name);
  294. if (index != -1)
  295. {
  296. return _elements[index].Value;
  297. }
  298. else
  299. {
  300. string message = string.Format("Element '{0}' not found.", name);
  301. throw new KeyNotFoundException(message);
  302. }
  303. }
  304. set
  305. {
  306. if (name == null)
  307. {
  308. throw new ArgumentNullException("name");
  309. }
  310. if (value == null)
  311. {
  312. throw new ArgumentNullException("value");
  313. }
  314. var index = IndexOfName(name);
  315. if (index != -1)
  316. {
  317. _elements[index] = new BsonElement(name, value);
  318. }
  319. else
  320. {
  321. Add(new BsonElement(name, value));
  322. }
  323. }
  324. }
  325. // public static methods
  326. /// <summary>
  327. /// Creates a new BsonDocument by mapping an object to a BsonDocument.
  328. /// </summary>
  329. /// <param name="value">The object to be mapped to a BsonDocument.</param>
  330. /// <returns>A BsonDocument.</returns>
  331. public new static BsonDocument Create(object value)
  332. {
  333. if (value == null)
  334. {
  335. throw new ArgumentNullException("value");
  336. }
  337. return (BsonDocument)BsonTypeMapper.MapToBsonValue(value, BsonType.Document);
  338. }
  339. /// <summary>
  340. /// Parses a JSON string and returns a BsonDocument.
  341. /// </summary>
  342. /// <param name="json">The JSON string.</param>
  343. /// <returns>A BsonDocument.</returns>
  344. public static BsonDocument Parse(string json)
  345. {
  346. using (var jsonReader = new JsonReader(json))
  347. {
  348. var context = BsonDeserializationContext.CreateRoot(jsonReader);
  349. var document = BsonDocumentSerializer.Instance.Deserialize(context);
  350. if (!jsonReader.IsAtEndOfFile())
  351. {
  352. throw new FormatException("String contains extra non-whitespace characters beyond the end of the document.");
  353. }
  354. return document;
  355. }
  356. }
  357. /// <summary>
  358. /// Tries to parse a JSON string and returns a value indicating whether it succeeded or failed.
  359. /// </summary>
  360. /// <param name="s">The JSON string.</param>
  361. /// <param name="result">The result.</param>
  362. /// <returns>Whether it succeeded or failed.</returns>
  363. public static bool TryParse(string s, out BsonDocument result)
  364. {
  365. try
  366. {
  367. result = Parse(s);
  368. return true;
  369. }
  370. catch
  371. {
  372. result = null;
  373. return false;
  374. }
  375. }
  376. // public methods
  377. /// <summary>
  378. /// Adds an element to the document.
  379. /// </summary>
  380. /// <param name="element">The element to add.</param>
  381. /// <returns>The document (so method calls can be chained).</returns>
  382. public virtual BsonDocument Add(BsonElement element)
  383. {
  384. var isDuplicate = IndexOfName(element.Name) != -1;
  385. if (isDuplicate && !_allowDuplicateNames)
  386. {
  387. var message = string.Format("Duplicate element name '{0}'.", element.Name);
  388. throw new InvalidOperationException(message);
  389. }
  390. else
  391. {
  392. _elements.Add(element);
  393. if (!isDuplicate)
  394. {
  395. if (_indexes == null)
  396. {
  397. RebuildIndexes();
  398. }
  399. else
  400. {
  401. _indexes.Add(element.Name, _elements.Count - 1); // index of the newly added element
  402. }
  403. }
  404. }
  405. return this;
  406. }
  407. /// <summary>
  408. /// Adds elements to the document from a dictionary of key/value pairs.
  409. /// </summary>
  410. /// <param name="dictionary">The dictionary.</param>
  411. /// <returns>The document (so method calls can be chained).</returns>
  412. [Obsolete("Use AddRange instead.")]
  413. public virtual BsonDocument Add(Dictionary<string, object> dictionary)
  414. {
  415. return AddRange(dictionary);
  416. }
  417. /// <summary>
  418. /// Adds elements to the document from a dictionary of key/value pairs.
  419. /// </summary>
  420. /// <param name="dictionary">The dictionary.</param>
  421. /// <param name="keys">Which keys of the hash table to add.</param>
  422. /// <returns>The document (so method calls can be chained).</returns>
  423. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  424. public virtual BsonDocument Add(Dictionary<string, object> dictionary, IEnumerable<string> keys)
  425. {
  426. return Add((IDictionary<string, object>)dictionary, keys);
  427. }
  428. /// <summary>
  429. /// Adds elements to the document from a dictionary of key/value pairs.
  430. /// </summary>
  431. /// <param name="dictionary">The dictionary.</param>
  432. /// <returns>The document (so method calls can be chained).</returns>
  433. [Obsolete("Use AddRange instead.")]
  434. public virtual BsonDocument Add(IDictionary<string, object> dictionary)
  435. {
  436. return AddRange(dictionary);
  437. }
  438. /// <summary>
  439. /// Adds elements to the document from a dictionary of key/value pairs.
  440. /// </summary>
  441. /// <param name="dictionary">The dictionary.</param>
  442. /// <param name="keys">Which keys of the hash table to add.</param>
  443. /// <returns>The document (so method calls can be chained).</returns>
  444. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  445. public virtual BsonDocument Add(IDictionary<string, object> dictionary, IEnumerable<string> keys)
  446. {
  447. if (dictionary == null)
  448. {
  449. throw new ArgumentNullException("dictionary");
  450. }
  451. if (keys == null)
  452. {
  453. throw new ArgumentNullException("keys");
  454. }
  455. foreach (var key in keys)
  456. {
  457. Add(key, BsonTypeMapper.MapToBsonValue(dictionary[key]));
  458. }
  459. return this;
  460. }
  461. /// <summary>
  462. /// Adds elements to the document from a dictionary of key/value pairs.
  463. /// </summary>
  464. /// <param name="dictionary">The dictionary.</param>
  465. /// <returns>The document (so method calls can be chained).</returns>
  466. [Obsolete("Use AddRange instead.")]
  467. public virtual BsonDocument Add(IDictionary dictionary)
  468. {
  469. return AddRange(dictionary);
  470. }
  471. /// <summary>
  472. /// Adds elements to the document from a dictionary of key/value pairs.
  473. /// </summary>
  474. /// <param name="dictionary">The dictionary.</param>
  475. /// <param name="keys">Which keys of the hash table to add.</param>
  476. /// <returns>The document (so method calls can be chained).</returns>
  477. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  478. public virtual BsonDocument Add(IDictionary dictionary, IEnumerable keys)
  479. {
  480. if (dictionary == null)
  481. {
  482. throw new ArgumentNullException("dictionary");
  483. }
  484. if (keys == null)
  485. {
  486. throw new ArgumentNullException("keys");
  487. }
  488. foreach (var key in keys)
  489. {
  490. if (key == null)
  491. {
  492. throw new ArgumentException("keys", "A key passed to BsonDocument.Add is null.");
  493. }
  494. if (key.GetType() != typeof(string))
  495. {
  496. throw new ArgumentOutOfRangeException("keys", "A key passed to BsonDocument.Add is not a string.");
  497. }
  498. Add((string)key, BsonTypeMapper.MapToBsonValue(dictionary[key]));
  499. }
  500. return this;
  501. }
  502. /// <summary>
  503. /// Adds a list of elements to the document.
  504. /// </summary>
  505. /// <param name="elements">The list of elements.</param>
  506. /// <returns>The document (so method calls can be chained).</returns>
  507. [Obsolete("Use AddRange instead.")]
  508. public virtual BsonDocument Add(IEnumerable<BsonElement> elements)
  509. {
  510. return AddRange(elements);
  511. }
  512. /// <summary>
  513. /// Adds a list of elements to the document.
  514. /// </summary>
  515. /// <param name="elements">The list of elements.</param>
  516. /// <returns>The document (so method calls can be chained).</returns>
  517. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  518. public virtual BsonDocument Add(params BsonElement[] elements)
  519. {
  520. return AddRange((IEnumerable<BsonElement>)elements);
  521. }
  522. /// <summary>
  523. /// Creates and adds an element to the document.
  524. /// </summary>
  525. /// <param name="name">The name of the element.</param>
  526. /// <param name="value">The value of the element.</param>
  527. /// <returns>The document (so method calls can be chained).</returns>
  528. public virtual BsonDocument Add(string name, BsonValue value)
  529. {
  530. if (name == null)
  531. {
  532. throw new ArgumentNullException("name");
  533. }
  534. if (value == null)
  535. {
  536. throw new ArgumentNullException("value");
  537. }
  538. Add(new BsonElement(name, value));
  539. return this;
  540. }
  541. /// <summary>
  542. /// Creates and adds an element to the document, but only if the condition is true.
  543. /// </summary>
  544. /// <param name="name">The name of the element.</param>
  545. /// <param name="value">The value of the element.</param>
  546. /// <param name="condition">Whether to add the element to the document.</param>
  547. /// <returns>The document (so method calls can be chained).</returns>
  548. public virtual BsonDocument Add(string name, BsonValue value, bool condition)
  549. {
  550. if (name == null)
  551. {
  552. throw new ArgumentNullException("name");
  553. }
  554. if (condition)
  555. {
  556. // don't check for null value unless condition is true
  557. if (value == null)
  558. {
  559. throw new ArgumentNullException("value");
  560. }
  561. Add(new BsonElement(name, value));
  562. }
  563. return this;
  564. }
  565. /// <summary>
  566. /// Creates and adds an element to the document, but only if the condition is true.
  567. /// If the condition is false the value factory is not called at all.
  568. /// </summary>
  569. /// <param name="name">The name of the element.</param>
  570. /// <param name="valueFactory">A delegate called to compute the value of the element if condition is true.</param>
  571. /// <param name="condition">Whether to add the element to the document.</param>
  572. /// <returns>The document (so method calls can be chained).</returns>
  573. public virtual BsonDocument Add(string name, Func<BsonValue> valueFactory, bool condition)
  574. {
  575. if (name == null)
  576. {
  577. throw new ArgumentNullException("name");
  578. }
  579. if (valueFactory == null)
  580. {
  581. throw new ArgumentNullException("valueFactory");
  582. }
  583. if (condition)
  584. {
  585. Add(new BsonElement(name, valueFactory()));
  586. }
  587. return this;
  588. }
  589. /// <summary>
  590. /// Adds elements to the document from a dictionary of key/value pairs.
  591. /// </summary>
  592. /// <param name="dictionary">The dictionary.</param>
  593. /// <returns>The document (so method calls can be chained).</returns>
  594. public virtual BsonDocument AddRange(Dictionary<string, object> dictionary)
  595. {
  596. return AddRange((IEnumerable<KeyValuePair<string, object>>)dictionary);
  597. }
  598. /// <summary>
  599. /// Adds elements to the document from a dictionary of key/value pairs.
  600. /// </summary>
  601. /// <param name="dictionary">The dictionary.</param>
  602. /// <returns>The document (so method calls can be chained).</returns>
  603. public virtual BsonDocument AddRange(IDictionary dictionary)
  604. {
  605. if (dictionary == null)
  606. {
  607. throw new ArgumentNullException("dictionary");
  608. }
  609. foreach (DictionaryEntry entry in dictionary)
  610. {
  611. if (entry.Key == null)
  612. {
  613. throw new ArgumentException("A key passed to BsonDocument.AddRange is null.", "keys");
  614. }
  615. if (entry.Key.GetType() != typeof(string))
  616. {
  617. throw new ArgumentOutOfRangeException("dictionary", "One or more keys in the dictionary passed to BsonDocument.AddRange is not a string.");
  618. }
  619. Add((string)entry.Key, BsonTypeMapper.MapToBsonValue(entry.Value));
  620. }
  621. return this;
  622. }
  623. /// <summary>
  624. /// Adds a list of elements to the document.
  625. /// </summary>
  626. /// <param name="elements">The list of elements.</param>
  627. /// <returns>The document (so method calls can be chained).</returns>
  628. public virtual BsonDocument AddRange(IEnumerable<BsonElement> elements)
  629. {
  630. if (elements == null)
  631. {
  632. throw new ArgumentNullException("elements");
  633. }
  634. foreach (var element in elements)
  635. {
  636. Add(element);
  637. }
  638. return this;
  639. }
  640. /// <summary>
  641. /// Adds elements to the document from a dictionary of key/value pairs.
  642. /// </summary>
  643. /// <param name="dictionary">The dictionary.</param>
  644. /// <returns>The document (so method calls can be chained).</returns>
  645. public virtual BsonDocument AddRange(IEnumerable<KeyValuePair<string, object>> dictionary)
  646. {
  647. if (dictionary == null)
  648. {
  649. throw new ArgumentNullException("dictionary");
  650. }
  651. foreach (var entry in dictionary)
  652. {
  653. Add(entry.Key, BsonTypeMapper.MapToBsonValue(entry.Value));
  654. }
  655. return this;
  656. }
  657. /// <summary>
  658. /// Clears the document (removes all elements).
  659. /// </summary>
  660. public virtual void Clear()
  661. {
  662. _elements.Clear();
  663. _indexes = null;
  664. }
  665. /// <summary>
  666. /// Creates a shallow clone of the document (see also DeepClone).
  667. /// </summary>
  668. /// <returns>A shallow clone of the document.</returns>
  669. public override BsonValue Clone()
  670. {
  671. BsonDocument clone = new BsonDocument();
  672. foreach (BsonElement element in _elements)
  673. {
  674. clone.Add(element.Clone());
  675. }
  676. return clone;
  677. }
  678. /// <summary>
  679. /// Compares this document to another document.
  680. /// </summary>
  681. /// <param name="rhs">The other document.</param>
  682. /// <returns>A 32-bit signed integer that indicates whether this document is less than, equal to, or greather than the other.</returns>
  683. public virtual int CompareTo(BsonDocument rhs)
  684. {
  685. if (rhs == null) { return 1; }
  686. // lhs and rhs might be subclasses of BsonDocument
  687. using (var lhsEnumerator = Elements.GetEnumerator())
  688. using (var rhsEnumerator = rhs.Elements.GetEnumerator())
  689. {
  690. while (true)
  691. {
  692. var lhsHasNext = lhsEnumerator.MoveNext();
  693. var rhsHasNext = rhsEnumerator.MoveNext();
  694. if (!lhsHasNext && !rhsHasNext) { return 0; }
  695. if (!lhsHasNext) { return -1; }
  696. if (!rhsHasNext) { return 1; }
  697. var lhsElement = lhsEnumerator.Current;
  698. var rhsElement = rhsEnumerator.Current;
  699. var result = lhsElement.Name.CompareTo(rhsElement.Name);
  700. if (result != 0) { return result; }
  701. result = lhsElement.Value.CompareTo(rhsElement.Value);
  702. if (result != 0) { return result; }
  703. }
  704. }
  705. }
  706. /// <summary>
  707. /// Compares the BsonDocument to another BsonValue.
  708. /// </summary>
  709. /// <param name="other">The other BsonValue.</param>
  710. /// <returns>A 32-bit signed integer that indicates whether this BsonDocument is less than, equal to, or greather than the other BsonValue.</returns>
  711. public override int CompareTo(BsonValue other)
  712. {
  713. if (other == null) { return 1; }
  714. var otherDocument = other as BsonDocument;
  715. if (otherDocument != null)
  716. {
  717. return CompareTo(otherDocument);
  718. }
  719. return CompareTypeTo(other);
  720. }
  721. /// <summary>
  722. /// Tests whether the document contains an element with the specified name.
  723. /// </summary>
  724. /// <param name="name">The name of the element to look for.</param>
  725. /// <returns>True if the document contains an element with the specified name.</returns>
  726. public virtual bool Contains(string name)
  727. {
  728. return IndexOfName(name) != -1;
  729. }
  730. /// <summary>
  731. /// Tests whether the document contains an element with the specified value.
  732. /// </summary>
  733. /// <param name="value">The value of the element to look for.</param>
  734. /// <returns>True if the document contains an element with the specified value.</returns>
  735. public virtual bool ContainsValue(BsonValue value)
  736. {
  737. if (value == null)
  738. {
  739. throw new ArgumentNullException("value");
  740. }
  741. return _elements.Any(e => e.Value == value);
  742. }
  743. /// <summary>
  744. /// Creates a deep clone of the document (see also Clone).
  745. /// </summary>
  746. /// <returns>A deep clone of the document.</returns>
  747. public override BsonValue DeepClone()
  748. {
  749. BsonDocument clone = new BsonDocument();
  750. foreach (BsonElement element in _elements)
  751. {
  752. clone.Add(element.DeepClone());
  753. }
  754. return clone;
  755. }
  756. /// <summary>
  757. /// Compares this document to another document.
  758. /// </summary>
  759. /// <param name="obj">The other document.</param>
  760. /// <returns>True if the two documents are equal.</returns>
  761. public bool Equals(BsonDocument obj)
  762. {
  763. return Equals((object)obj); // handles obj == null correctly
  764. }
  765. /// <summary>
  766. /// Compares this BsonDocument to another object.
  767. /// </summary>
  768. /// <param name="obj">The other object.</param>
  769. /// <returns>True if the other object is a BsonDocument and equal to this one.</returns>
  770. public override bool Equals(object obj)
  771. {
  772. if (object.ReferenceEquals(obj, null) || !(obj is BsonDocument)) { return false; }
  773. // lhs and rhs might be subclasses of BsonDocument
  774. var rhs = (BsonDocument)obj;
  775. return Elements.SequenceEqual(rhs.Elements);
  776. }
  777. /// <summary>
  778. /// Gets an element of this document.
  779. /// </summary>
  780. /// <param name="index">The zero based index of the element.</param>
  781. /// <returns>The element.</returns>
  782. public virtual BsonElement GetElement(int index)
  783. {
  784. return _elements[index];
  785. }
  786. /// <summary>
  787. /// Gets an element of this document.
  788. /// </summary>
  789. /// <param name="name">The name of the element.</param>
  790. /// <returns>A BsonElement.</returns>
  791. public virtual BsonElement GetElement(string name)
  792. {
  793. if (name == null)
  794. {
  795. throw new ArgumentNullException("name");
  796. }
  797. var index = IndexOfName(name);
  798. if (index != -1)
  799. {
  800. return _elements[index];
  801. }
  802. else
  803. {
  804. string message = string.Format("Element '{0}' not found.", name);
  805. throw new KeyNotFoundException(message);
  806. }
  807. }
  808. /// <summary>
  809. /// Gets an enumerator that can be used to enumerate the elements of this document.
  810. /// </summary>
  811. /// <returns>An enumerator.</returns>
  812. public virtual IEnumerator<BsonElement> GetEnumerator()
  813. {
  814. return _elements.GetEnumerator();
  815. }
  816. /// <summary>
  817. /// Gets the hash code.
  818. /// </summary>
  819. /// <returns>The hash code.</returns>
  820. public override int GetHashCode()
  821. {
  822. return new Hasher()
  823. .Hash(BsonType)
  824. .HashElements(Elements)
  825. .GetHashCode();
  826. }
  827. /// <summary>
  828. /// Gets the value of an element.
  829. /// </summary>
  830. /// <param name="index">The zero based index of the element.</param>
  831. /// <returns>The value of the element.</returns>
  832. public virtual BsonValue GetValue(int index)
  833. {
  834. return this[index];
  835. }
  836. /// <summary>
  837. /// Gets the value of an element.
  838. /// </summary>
  839. /// <param name="name">The name of the element.</param>
  840. /// <returns>The value of the element.</returns>
  841. public virtual BsonValue GetValue(string name)
  842. {
  843. if (name == null)
  844. {
  845. throw new ArgumentNullException("name");
  846. }
  847. return this[name];
  848. }
  849. /// <summary>
  850. /// Gets the value of an element or a default value if the element is not found.
  851. /// </summary>
  852. /// <param name="name">The name of the element.</param>
  853. /// <param name="defaultValue">The default value returned if the element is not found.</param>
  854. /// <returns>The value of the element or the default value if the element is not found.</returns>
  855. public virtual BsonValue GetValue(string name, BsonValue defaultValue)
  856. {
  857. if (name == null)
  858. {
  859. throw new ArgumentNullException("name");
  860. }
  861. var index = IndexOfName(name);
  862. if (index != -1)
  863. {
  864. return _elements[index].Value;
  865. }
  866. else
  867. {
  868. return defaultValue;
  869. }
  870. }
  871. /// <summary>
  872. /// Gets the index of an element.
  873. /// </summary>
  874. /// <param name="name">The name of the element.</param>
  875. /// <returns>The index of the element, or -1 if the element is not found.</returns>
  876. public virtual int IndexOfName(string name)
  877. {
  878. if (_indexes == null)
  879. {
  880. var count = _elements.Count;
  881. for (var index = 0; index < count; index++)
  882. {
  883. if (_elements[index].Name == name)
  884. {
  885. return index;
  886. }
  887. }
  888. return -1;
  889. }
  890. else
  891. {
  892. int index;
  893. if (_indexes.TryGetValue(name, out index))
  894. {
  895. return index;
  896. }
  897. else
  898. {
  899. return -1;
  900. }
  901. }
  902. }
  903. /// <summary>
  904. /// Inserts a new element at a specified position.
  905. /// </summary>
  906. /// <param name="index">The position of the new element.</param>
  907. /// <param name="element">The element.</param>
  908. public virtual void InsertAt(int index, BsonElement element)
  909. {
  910. var isDuplicate = IndexOfName(element.Name) != -1;
  911. if (isDuplicate && !_allowDuplicateNames)
  912. {
  913. var message = string.Format("Duplicate element name '{0}' not allowed.", element.Name);
  914. throw new InvalidOperationException(message);
  915. }
  916. else
  917. {
  918. _elements.Insert(index, element);
  919. RebuildIndexes();
  920. }
  921. }
  922. /// <summary>
  923. /// Merges another document into this one. Existing elements are not overwritten.
  924. /// </summary>
  925. /// <param name="document">The other document.</param>
  926. /// <returns>The document (so method calls can be chained).</returns>
  927. public virtual BsonDocument Merge(BsonDocument document)
  928. {
  929. Merge(document, false); // don't overwriteExistingElements
  930. return this;
  931. }
  932. /// <summary>
  933. /// Merges another document into this one, specifying whether existing elements are overwritten.
  934. /// </summary>
  935. /// <param name="document">The other document.</param>
  936. /// <param name="overwriteExistingElements">Whether to overwrite existing elements.</param>
  937. /// <returns>The document (so method calls can be chained).</returns>
  938. public virtual BsonDocument Merge(BsonDocument document, bool overwriteExistingElements)
  939. {
  940. if (document == null)
  941. {
  942. throw new ArgumentNullException("document");
  943. }
  944. foreach (BsonElement element in document)
  945. {
  946. if (overwriteExistingElements || !Contains(element.Name))
  947. {
  948. this[element.Name] = element.Value;
  949. }
  950. }
  951. return this;
  952. }
  953. /// <summary>
  954. /// Removes an element from this document (if duplicate element names are allowed
  955. /// then all elements with this name will be removed).
  956. /// </summary>
  957. /// <param name="name">The name of the element to remove.</param>
  958. public virtual void Remove(string name)
  959. {
  960. if (name == null)
  961. {
  962. throw new ArgumentNullException("name");
  963. }
  964. if (_allowDuplicateNames)
  965. {
  966. var count = _elements.Count;
  967. var removedAny = false;
  968. for (var i = count - 1; i >= 0; i--)
  969. {
  970. if (_elements[i].Name == name)
  971. {
  972. _elements.RemoveAt(i);
  973. removedAny = true;
  974. }
  975. }
  976. if (removedAny)
  977. {
  978. RebuildIndexes();
  979. }
  980. }
  981. else
  982. {
  983. var index = IndexOfName(name);
  984. if (index != -1)
  985. {
  986. _elements.RemoveAt(index);
  987. RebuildIndexes();
  988. }
  989. }
  990. }
  991. /// <summary>
  992. /// Removes an element from this document.
  993. /// </summary>
  994. /// <param name="index">The zero based index of the element to remove.</param>
  995. public virtual void RemoveAt(int index)
  996. {
  997. _elements.RemoveAt(index);
  998. RebuildIndexes();
  999. }
  1000. /// <summary>
  1001. /// Removes an element from this document.
  1002. /// </summary>
  1003. /// <param name="element">The element to remove.</param>
  1004. public virtual void RemoveElement(BsonElement element)
  1005. {
  1006. if (_elements.Remove(element))
  1007. {
  1008. RebuildIndexes();
  1009. }
  1010. }
  1011. /// <summary>
  1012. /// Sets the value of an element.
  1013. /// </summary>
  1014. /// <param name="index">The zero based index of the element whose value is to be set.</param>
  1015. /// <param name="value">The new value.</param>
  1016. /// <returns>The document (so method calls can be chained).</returns>
  1017. public virtual BsonDocument Set(int index, BsonValue value)
  1018. {
  1019. if (value == null)
  1020. {
  1021. throw new ArgumentNullException("value");
  1022. }
  1023. this[index] = value;
  1024. return this;
  1025. }
  1026. /// <summary>
  1027. /// Sets the value of an element (an element will be added if no element with this name is found).
  1028. /// </summary>
  1029. /// <param name="name">The name of the element whose value is to be set.</param>
  1030. /// <param name="value">The new value.</param>
  1031. /// <returns>The document (so method calls can be chained).</returns>
  1032. public virtual BsonDocument Set(string name, BsonValue value)
  1033. {
  1034. if (name == null)
  1035. {
  1036. throw new ArgumentNullException("name");
  1037. }
  1038. if (value == null)
  1039. {
  1040. throw new ArgumentNullException("value");
  1041. }
  1042. this[name] = value;
  1043. return this;
  1044. }
  1045. /// <summary>
  1046. /// Sets an element of the document (replacing the existing element at that position).
  1047. /// </summary>
  1048. /// <param name="index">The zero based index of the element to replace.</param>
  1049. /// <param name="element">The new element.</param>
  1050. /// <returns>The document.</returns>
  1051. public virtual BsonDocument SetElement(int index, BsonElement element)
  1052. {
  1053. var oldName = _elements[index].Name;
  1054. _elements[index] = element;
  1055. if (element.Name != oldName)
  1056. {
  1057. RebuildIndexes();
  1058. }
  1059. return this;
  1060. }
  1061. /// <summary>
  1062. /// Sets an element of the document (replaces any existing element with the same name or adds a new element if an element with the same name is not found).
  1063. /// </summary>
  1064. /// <param name="element">The new element.</param>
  1065. /// <returns>The document.</returns>
  1066. public virtual BsonDocument SetElement(BsonElement element)
  1067. {
  1068. var index = IndexOfName(element.Name);
  1069. if (index != -1)
  1070. {
  1071. _elements[index] = element;
  1072. }
  1073. else
  1074. {
  1075. Add(element);
  1076. }
  1077. return this;
  1078. }
  1079. /// <summary>
  1080. /// Converts the BsonDocument to a Dictionary&lt;string, object&gt;.
  1081. /// </summary>
  1082. /// <returns>A dictionary.</returns>
  1083. public Dictionary<string, object> ToDictionary()
  1084. {
  1085. var options = new BsonTypeMapperOptions
  1086. {
  1087. DuplicateNameHandling = DuplicateNameHandling.ThrowException,
  1088. MapBsonArrayTo = typeof(object[]), // TODO: should this be List<object>?
  1089. MapBsonDocumentTo = typeof(Dictionary<string, object>),
  1090. MapOldBinaryToByteArray = false
  1091. };
  1092. return (Dictionary<string, object>)BsonTypeMapper.MapToDotNetValue(this, options);
  1093. }
  1094. /// <summary>
  1095. /// Converts the BsonDocument to a Hashtable.
  1096. /// </summary>
  1097. /// <returns>A hashtable.</returns>
  1098. public Hashtable ToHashtable()
  1099. {
  1100. var options = new BsonTypeMapperOptions
  1101. {
  1102. DuplicateNameHandling = DuplicateNameHandling.ThrowException,
  1103. MapBsonArrayTo = typeof(object[]), // TODO: should this be ArrayList?
  1104. MapBsonDocumentTo = typeof(Hashtable),
  1105. MapOldBinaryToByteArray = false
  1106. };
  1107. return (Hashtable)BsonTypeMapper.MapToDotNetValue(this, options);
  1108. }
  1109. /// <summary>
  1110. /// Returns a string representation of the document.
  1111. /// </summary>
  1112. /// <returns>A string representation of the document.</returns>
  1113. public override string ToString()
  1114. {
  1115. return this.ToJson();
  1116. }
  1117. /// <summary>
  1118. /// Tries to get an element of this document.
  1119. /// </summary>
  1120. /// <param name="name">The name of the element.</param>
  1121. /// <param name="value">The element.</param>
  1122. /// <returns>True if an element with that name was found.</returns>
  1123. public virtual bool TryGetElement(string name, out BsonElement value)
  1124. {
  1125. if (name == null)
  1126. {
  1127. throw new ArgumentNullException("name");
  1128. }
  1129. var index = IndexOfName(name);
  1130. if (index != -1)
  1131. {
  1132. value = _elements[index];
  1133. return true;
  1134. }
  1135. else
  1136. {
  1137. value = default(BsonElement);
  1138. return false;
  1139. }
  1140. }
  1141. /// <summary>
  1142. /// Tries to get the value of an element of this document.
  1143. /// </summary>
  1144. /// <param name="name">The name of the element.</param>
  1145. /// <param name="value">The value of the element.</param>
  1146. /// <returns>True if an element with that name was found.</returns>
  1147. public virtual bool TryGetValue(string name, out BsonValue value)
  1148. {
  1149. if (name == null)
  1150. {
  1151. throw new ArgumentNullException("name");
  1152. }
  1153. var index = IndexOfName(name);
  1154. if (index != -1)
  1155. {
  1156. value = _elements[index].Value;
  1157. return true;
  1158. }
  1159. else
  1160. {
  1161. value = null;
  1162. return false;
  1163. }
  1164. }
  1165. // private methods
  1166. private void RebuildIndexes()
  1167. {
  1168. if (_elements.Count < __indexesThreshold)
  1169. {
  1170. _indexes = null;
  1171. return;
  1172. }
  1173. if (_indexes == null)
  1174. {
  1175. _indexes = new Dictionary<string, int>();
  1176. }
  1177. else
  1178. {
  1179. _indexes.Clear();
  1180. }
  1181. // process the elements in reverse order so that in case of duplicates the dictionary ends up pointing at the first one
  1182. var count = _elements.Count;
  1183. for (int index = count - 1; index >= 0; index--)
  1184. {
  1185. BsonElement element = _elements[index];
  1186. _indexes[element.Name] = index;
  1187. }
  1188. }
  1189. // explicit interface implementations
  1190. BsonDocument IConvertibleToBsonDocument.ToBsonDocument()
  1191. {
  1192. return this;
  1193. }
  1194. IEnumerator IEnumerable.GetEnumerator()
  1195. {
  1196. return GetEnumerator();
  1197. }
  1198. }
  1199. }