简体   繁体   中英

Get nested object that has a value in mongodb c#

I'm trying to retrieve a nested object where the key exists and have tried so many different filters/builders, but still unable to get it working properly.

Here's what I have lately:

var filter = "{ Properties : { " + propName + ": { $exists: true } } }";
var results = coll.Find(filter).ToList();

where propName is a string variable.

The db content looks like this:

{
    "_id" : ObjectId("5aaa1e72884cd35eef175c6a"),
    "Hash" : 1164917297,
    "Name" : "N3N_ZN1",
    "Description" : null,
    "Label" : "N3N_ZN1",
    "RelationSource" : {
        "From" : [],
        "To" : [],
        "Pair" : []
    },
    "Relations" : {},
    "Properties" : {
        "SOPName" : [ 
            "SOP for Intrusion"
        ]
    },
    "ObjectTypeName" : "ultrasonic",
    "PlayerTypeName" : null,
    "PlayerProperties" : null
}

My objective is to retrieve all documents where SOPName exists. The Properties object is dynamic, so SOPName key may not exist in all documents.

Oh, and the query I have above isn't retrieving any documents in my db (Count 0). Any ideas?

Okay, resolved this using:

    var coll = DatabaseCommon.Instance.GetDatabase("ps_" + siteId).GetCollection<BsonDocument>("Object");
    var filter = "{ 'Properties." + propName + "' : { '$exists': true } }";
    var results = coll.Find(filter).ToList();

The filter doesn't work as a typical nested object...this FAILS:

var filter = "{ Properties : { " + propName + " : { '$exists': true } } }";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM