Sarika Kondra
Sarika Kondra

Reputation: 11

Querying on arrays in MongoDB C#

I have a collection with following document type:

{
 field1: 1,
 field2: "test1",
 field3: [1,2,3]
}

Suppose I have the following documents in my collection (ignoring field1 and field2 and only considering field3)

Collection:

doc1-  {...
        field3: [3,4,5,6]
       }
doc2-  {...
        field3: [3,4]
       }
doc3-  {...
        field3: [1,2,3]
       }
doc4-  {...
        field3: [3,6,7]
       }

Now, I am querying on this collection on field3 with values [3,4,6,7].

So, I execute a query in the collection in such a way that I should get all documents that have all its array elements present in the query array. In my case, it should return the documents doc2 and doc4, since all its elements of field3 are existing in the query, but Query.ALL doesn't work.

How can I accomplish this in MongoDB querying?

(edited for more clarity)

Why $all does'nt work?

EX: If my questioning array is [3,4], when I use Query.All("field3",new BsonValue[]{3,4}), I will get all the documents with "field3" having all the elements in the questioning array i.e., 3 and 4. So In such case my result docs would be doc1 and doc2 from example above. But my requirement is only doc2. Because all the elements of my document should be there in my query array and not the other way.

Why $in does'nt work? If atleast one element of the quetiong array is present in the document it is retrieved. Ex: questioning array is [3,4], when I use Query.In("field3",new BsonValue[]{3,4}), result will be all 4 documents of collection doc1, doc2, doc3 and doc4

Upvotes: 1

Views: 1776

Answers (1)

Alberto Solano
Alberto Solano

Reputation: 8227

Take a look at this question.

The operator All in the C# driver or $all in MongoDb considers all the elements, as explained here in the documentation:

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

Then, supposing the elements 3 and 4, the operators considers arrays, with this logic: the array contains elements 3 AND 4.

I think you should use then the Query.In (further info about $in here) if you want to consider arrays with 3 OR 4.

UPDATE

After your clarification, I noticed this request in the MongoDb's site. In that page, the user requested a feature in order to retrieve only the documents with an array that contains only specified elements, but this is not possible actually.

Unfortunately, I think, this is a limitation of MongoDb and, in general, of NoSQL databases.

Upvotes: 1

Related Questions