BsonDocument.cs 49 KB

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