Tuesday 15 January 2013

How do I find documents with an element at a particular position in an array using MongoDB? -


I would like to search all the documents where element <0> element <0 code is apple . So I want to get the document 1 and 3, but not 2. Is there such a thing possibly in Mongo?

As an example it does not make any sense, but my application was very complex to present here.

  {_id = & gt; 1 name = & gt; 'Best Smooth Content' = & gt; Array ([0] = & gt; Apple [1] = & gt; Raspberry [2] => orange [3] = & gt; banana)}   

  {_id = & gt; 2 name = & gt; 'Summer in summer' element = & gt; Array ([0] = & gt; Lemon [1] = & gt; Mint [2] = & gt; Apple)}   

  _id = & gt; ; 3 name = & gt; 'Yogurt sugar' element => Array ([0] = & gt; Apple [1] => Blueberry)}   

Example borrowed -

You can use the array position operator () What is useful is that you can use the same pattern and use the normal $ syntax You can specify a specific index instead of

assuming your data is:

  & gt; Db.so1.insert ({Name: "Best Smooth", Component: ['apple', 'raspberry', 'orange', 'banana']}) gt; Db.so1.insert ({name: "smooth in summer", content: ['lemon', 'mint', 'apple']} gt; Db.so1.insert ({name: "yogurt smoothie", content: ['apple', 'blueberry']})   

If you only want to limit the search for index status 0 , just add the array property name as shown below:

  & gt; Db.so1.find ({'ingredients.0': 'apple'})   

Result:

  {"_id": ObjectId ("51c4425ff227e278e59f5df5 {"_id"}: Object ID ("51c4428af227e278e59f5df7"), "name": "best smooth", "content": ["apple", "raspberry", "orange", "banana"]} "Curd sugar", "organ": ["apple", "blueberry"]}    

No comments:

Post a Comment